可以使用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);
}
关键是如果要在单个调用中执行多个查询,则 必须 使用MysqLi_multi_query
。出于安全原因,MysqLi_query
将不执行多个查询以防止sql注入。
还请记住的行为MysqLi_store_result
。它返回FALSE
如果查询没有结果集(这INSERT
查询不),所以你还必须检查MysqLi_error
地看到,它返回一个空字符串意味着INSERT
成功。