我有这段代码:
//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
不确定错误是什么,所有语法似乎都是正确的。感谢。
答案 0 :(得分: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);
}
或者正如安德鲁斯所提到的,内爆方法:
//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);
}