2013-08-30 35 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

相关问题