2013-02-25 47 views
2

嗨,大家好,我嘗試存儲問題&答案在2和表1個使用SQL查詢:SQL查詢使用多個插件和多LAST_INSERT_ID()的工作不

INSERT INTO questions (question, level_ID) VALUES ('hello', '1'); INSERT INTO answers (questions_ID, answer, ok) VALUES (LAST_INSERT_ID(),'doei',0), (LAST_INSERT_ID(),'ciao',1); 

如果我執行代碼的phpMyAdmin的SQL箱它工作得很好,但如果我在PHP代碼生成腳本,執行它,它返回以下錯誤:

您的SQL語法錯誤;檢查與您的MySQL服務器版本對應的手冊,以便在'INSERT INTO answers(questions_ID,answer,ok)'附近使用正確的語法。'VALUE(LAST_INSERT_ID(),'doei',0'at line 2

我無法'看不到我在做什麼錯了...任何人??

在此先感謝。

+0

顯示你的PHP代碼。 – Karl 2013-02-25 11:21:59

+0

我的猜測是,您在一次調用中執行所有查詢,但是您使用的庫不支持多個語句。 – 2013-02-25 11:24:45

回答

1

它不是SQL查詢而設置的查詢。
phpMyAdmin的只是分割你的一套,然後分別執行查詢。

所以,你必須做的。
只要運行他們一個接一個。

不要改變任何東西。不需要額外的變量或其他。
只需在2個單獨的連續調用中一個接一個地運行相同的查詢。
就是這樣。

+2

...或使用[mysqli :: multi_query()](http://php.net/manual/en/mysqli.multi-query.php)。 – 2013-02-25 11:25:25

+0

好男人謝謝。如果我分開查詢並單獨運行,確實可行。但是因爲我需要從LAST_INSERT_ID()生成的ID我把查詢放在一起。所以現在我必須使用一個變量來存儲生成的ID? – 2013-02-25 11:38:04

+0

@ArjoPost是的,你需要一個變量傳遞給第二個SQL。你完成了。 – Hamad 2013-02-25 11:57:12

0

the manual

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

所以你不需要只要你使用相同的連接收拾所有查詢到一個SQL數據庫調用。但是如果你想想要這樣做,你需要確保你的數據庫庫和函數支持該功能。