
多個 mysqli 查詢:了解 mysqli_multi_query()
使用 MySQLi,在單一請求中執行多個查詢並不簡單。嘗試執行單獨的 mysqli_query() 呼叫將導致僅執行第一個查詢。為了克服這個限制,mysqli_multi_query() 提供了一個一次執行多個 SQL 語句的解決方案。
範例實作:
考慮以下場景:
1 2 | mysqli_query( $dblink , "INSERT INTO images ..." );
mysqli_query( $dblink , "INSERT INTO images_history ..." );
|
登入後複製
要同時執行兩個查詢,請使用mysqli_multi_query():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | $mysqli = new mysqli(...);
$query = "INSERT INTO images ..." ;
$query .= "INSERT INTO images_history ..." ;
$result = mysqli_multi_query( $mysqli , $query );
if ( $result ) {
while (mysqli_more_results( $mysqli ) && mysqli_next_result( $mysqli )) {
if (( $result = mysqli_store_result( $mysqli )) === false && mysqli_error( $mysqli ) != '' ) {
echo "Query failed: " . mysqli_error( $mysqli );
}
}
} else {
echo "First query failed..." . mysqli_error( $mysqli );
}
|
登入後複製
關鍵注意事項:
- 關鍵注意事項:
-
- 需要需要🎜一個包含所有用分號(;) 分隔的查詢的字串。
mysqli_store_result() 必須用於檢索每個查詢的結果。由於 INSERT 查詢不傳回結果集,請檢查 mysqli_error() 是否有空字串以確認插入是否成功。
這種方法是安全的,因為它可以防止執行多個 mysqli_query() 呼叫時出現 SQL 注入。
- 額外資源:
-
- [mysqli_multi_query](https://www.php.net/manual/en/myi.multi-query .php)
- [mysqli_more_results]( https://www.php.net/manual/en/mysqli.more-results .php)
[mysqli_next_result](https://www.php.net/manual/en/mysqli.next- result.php)[mysqli_store_result](https://www .php.net/manual/en/mysqli.store-result.php)
以上是如何在 PHP 中同時執行多個 MySQLi 查詢?的詳細內容。更多資訊請關注PHP中文網其他相關文章!