9

そのように2つのmysqliクエリを持つことは可能ですか?

mysqli_query($dblink, "INSERT INTO images (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName')");
mysqli_query($dblink, "INSERT INTO images_history (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name, day, month, year) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName', '$day', '$month', '$year')");

基本的に、DB 内の 2 つのテーブルを更新したいと考えています。これを行うより良い方法はありますか?

4

3 に答える 3

27

mysqli_multi_query()で可能です。

例:

<?php

$mysqli = new mysqli($host, $user, $password, $database);

// create string of queries separated by ;
$query  = "INSERT INTO images (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName');";
$query .= "INSERT INTO images_history (project_id, user_id, image_name, date_created, link_to_file, link_to_thumbnail, given_name, day, month, year) VALUES ('$project_id', '$user_id', '$image_name', '$date_created', '$link_to_file', '$thumbnail', '$ImageName', '$day', '$month', '$year');";

// execute query - $result is false if the first query failed
$result = mysqli_multi_query($mysqli, $query);

if ($result) {
    do {
        // grab the result of the next query
        if (($result = mysqli_store_result($mysqli)) === false && mysqli_error($mysqli) != '') {
            echo "Query failed: " . mysqli_error($mysqli);
        }
    } while (mysqli_more_results($mysqli) && mysqli_next_result($mysqli)); // while there are more results
} else {
    echo "First query failed..." . mysqli_error($mysqli);
}

重要なのは、1 回の呼び出しで複数のクエリを実行する場合に使用する必要があることです。mysqli_multi_queryセキュリティ上の理由から、mysqli_querySQL インジェクションを防ぐために複数のクエリを実行しません。

の振る舞いにも注意してmysqli_store_resultください。クエリに結果セットがない場合に返さFALSEれるため (どのINSERTクエリにもありません)、成功しmysqli_errorたことを意味する空の文字列が返されることも確認する必要がありますINSERT

参照:
mysqli_multi_query
mysqli_more_results
mysqli_next_result
mysqli_store_result

于 2012-06-07T00:54:11.267 に答える