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_query
SQL インジェクションを防ぐために複数のクエリを実行しません。
の振る舞いにも注意してmysqli_store_result
ください。クエリに結果セットがない場合に返さFALSE
れるため (どのINSERT
クエリにもありません)、成功しmysqli_error
たことを意味する空の文字列が返されることも確認する必要がありますINSERT
。
参照:
mysqli_multi_query
mysqli_more_results
mysqli_next_result
mysqli_store_result