1

私はこのコードを持っています:

//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

1 に答える 1

2

マルチクエリステートメントにセミコロンがありません。

.=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 が述べたように、implode メソッド:

//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);
}
于 2013-08-30T19:33:53.543 に答える