2013-08-30 62 views
1

我有這樣的代碼:MySQL的LAST_INSERT_ID語法

//insert user input into db 
$query = "INSERT INTO test_details (test_title, user_id, likes) 
VALUES ('$title', '$user_id', '0')"; 
$query .= "INSERT INTO test_descriptions (test_id, description) 
VALUES (LAST_INSERT_ID(), '$description')"; 
if(isset($grade) && isset($difficulty) && isset($subject)) { 
    $query .= "INSERT INTO test_filters (test_id, grade, subject, difficulty) 
    VALUES (LAST_INSERT_ID(), '$grade', '$subject', '$difficulty')"; 
} 
if(mysqli_multi_query($con, $query)) { 
    echo 'Go <a href="../create">back</a> to start creating questions.'; 
} 
else { 
    echo "An error occurred! Try again later."; 
    echo mysqli_error($con); 
} 

當我嘗試執行代碼,我收到此MySQL錯誤:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @id = (SELECT LAST_INSERT_ID())INSERT INTO test_descriptions (test_id, descr' at line 2不知道做了什麼錯,所有的語法似乎是正確的。謝謝。

+4

你需要每個單獨的SQL語句之間添加分號。 – andrewsi

+1

您的錯誤消息包含未出現在代碼摘錄中的SQL片段('SET @id ...')。我錯過了什麼,或者你是? – pilcrow

回答

2

你在你的mutli-query語句中缺少分號。

爲了一致性,您可以將它們添加到要連接的查詢前(.=),因爲if語句可能會或可能不會將查詢添加到混合中。

//insert user input into db 
$query = "INSERT INTO test_details (test_title, user_id, likes) 
VALUES ('$title', '$user_id', '0')"; 
$query .= ";INSERT INTO test_descriptions (test_id, description) 
VALUES (LAST_INSERT_ID(), '$description')"; 
if(isset($grade) && isset($difficulty) && isset($subject)) { 
    $query .= ";INSERT INTO test_descriptions (test_id, grade, subject, difficulty) 
    VALUES (LAST_INSERT_ID(), '$grade', '$subject', '$difficulty')"; 
} 
if(mysqli_multi_query($con, $query)) { 
    echo 'Go <a href="../create">back</a> to start creating questions.'; 
} 
else { 
    echo "An error occurred! Try again later."; 
    echo mysqli_error($con); 
} 

或者像andrewsi提到的,​​破滅方法:

//insert user input into db 
$query[] = "INSERT INTO test_details (test_title, user_id, likes) 
VALUES ('$title', '$user_id', '0')"; 
$query[] = "INSERT INTO test_descriptions (test_id, description) 
VALUES (LAST_INSERT_ID(), '$description')"; 
if(isset($grade) && isset($difficulty) && isset($subject)) { 
    $query[] = "INSERT INTO test_descriptions (test_id, grade, subject, difficulty) 
    VALUES (LAST_INSERT_ID(), '$grade', '$subject', '$difficulty')"; 
} 
if(mysqli_multi_query($con, implode(';', $query))) { 
    echo 'Go <a href="../create">back</a> to start creating questions.'; 
} 
else { 
    echo "An error occurred! Try again later."; 
    echo mysqli_error($con); 
} 
+1

您還可以將單獨的語句添加到數組中,然後使用分號作爲膠水將其「implode」。 – andrewsi

+0

感謝您提供兩種解決方案,我習慣於一直使用mysqli_query。將接受爲正確答案。 – Tom

+0

另外,爲什麼在查詢前添加分號?該代碼將在最後使用分號。 – Tom

相關問題