mysqli::multi_query
(mysqli_multi_query)對數據庫執行查詢
multi_query() / mysqli_multi_query()函數對數據庫執行一個或多個查詢。查詢之間用分號分隔。
對數據庫執行多個查詢:
<?php
$mysqli = new mysqli ( "localhost" , "my_user" , "my_password" , "my_db" ) ;
if ( $mysqli -> connect_errno ) {
echo "Failed to connect to MySQL: " . $mysqli -> connect_error ;
exit ( ) ;
}
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;" ;
$sql .= "SELECT Country FROM Customers" ;
// 執行多查詢
if ( $mysqli -> multi_query ( $sql ) ) {
do {
// 存儲第一個結果集
if ( $result = $mysqli -> store_result ( ) ) {
while ( $row = $result -> fetch_row ( ) ) {
printf ( "%s\n" , $row [ 0 ] ) ;
}
$result -> free_result ( ) ;
}
// 如果有更多的結果集,則打印分隔符
if ( $mysqli -> more_results ( ) ) {
printf ( "-------------\n" ) ;
}
// 準備下一個結果集
} while ( $mysqli -> next_result ( ) ) ;
}
$mysqli -> close ( ) ;
?>
對數據庫執行多個查詢:
<?php
$con = mysqli_connect ( "localhost" , "my_user" , "my_password" , "my_db" ) ;
if ( mysqli_connect_errno ( ) ) {
echo "Failed to connect to MySQL: " . mysqli_connect_error ( ) ;
exit ( ) ;
}
$sql = "SELECT Lastname FROM Persons ORDER BY LastName;" ;
$sql .= "SELECT Country FROM Customers" ;
// 執行多查詢
if ( mysqli_multi_query ( $con , $sql ) ) {
do {
// 存儲第一個結果集
if ( $result = mysqli_store_result ( $con ) ) {
while ( $row = mysqli_fetch_row ( $result ) ) {
printf ( "%s\n" , $row [ 0 ] ) ;
}
mysqli_free_result ( $result ) ;
}
// 如果有更多的結果集,則打印分隔符
if ( mysqli_more_results ( $con ) ) {
printf ( "-------------\n" ) ;
}
// 準備下一個結果集
} while ( mysqli_next_result ( $con ) ) ;
}
mysqli_close ( $con ) ;
?>