繁体   English   中英

MySQL Last_Insert_ID语法

[英]MySQL Last_Insert_ID Syntax

我有以下代码:

//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 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不确定做错了什么,所有语法似乎是的,谢谢。

您在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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM