問題描述
是否可以像這樣有兩個 mysqli 查詢?
Is it possible to have two mysqli queries like so?
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')");
基本上我想更新我的數據庫中的兩個表.有沒有更好的方法來做到這一點?
Basically I want to update two tables in my DB. Is there a better way to do this?
推薦答案
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 注入.
The key is that you must use mysqli_multi_query
if you want to execute more than one query in a single call. For security reasons, mysqli_query
will not execute multiple queries to prevent SQL injections.
還要記住 mysqli_store_result
的行為.如果查詢沒有結果集(INSERT
查詢沒有),它返回 FALSE
所以你還必須檢查 mysqli_error
以查看它返回一個空字符串表示 INSERT
成功.
Also keep in mind the behavior of mysqli_store_result
. It returns FALSE
if the query has no result set (which INSERT
queries do not) so you must also check mysqli_error
to see that it returns an empty string meaning the INSERT
was successful.
見:
mysqli_multi_query
mysqli_more_results
mysqli_next_result
mysqli_store_result
這篇關于為什么我不能運行兩個 mysqli 查詢?第二個失敗的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!