Hàm multi_query () trong PHP mysqli
Ví dụ - Kiểu hướng đối tượng
Thực hiện nhiều truy vấn đối với cơ sở dữ liệu:
<?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";
// Execute multi query
if ($mysqli
-> multi_query($sql)) {
do {
// Store first result set
if ($result =
$mysqli -> store_result()) {
while ($row =
$result -> fetch_row()) {
printf("%s\n", $row[0]);
}
$result
-> free_result();
}
// if there are more result-sets, the print a
divider
if ($mysqli -> more_results()) {
printf("-------------\n");
}
//Prepare next result set
} while ($mysqli
-> next_result());
}
$mysqli -> close();
?>
Xem ví dụ về phong cách thủ tục ở dưới cùng.
Định nghĩa và Cách sử dụng
Hàm multi_query () / mysqli_multi_query () thực hiện một hoặc nhiều truy vấn đối với cơ sở dữ liệu. Các truy vấn được phân tách bằng dấu chấm phẩy.
Cú pháp
Phong cách hướng đối tượng:
$mysqli ->
multi_query(query)
Phong cách thủ tục:
mysqli_multi_query(connection, query)
Giá trị tham số
Parameter | Description |
---|---|
connection | Required. Specifies the MySQL connection to use |
query | Required. Specifies one or more queries, separated with semicolon |
Chi tiết kỹ thuật
Giá trị trả lại: | FALSE nếu truy vấn đầu tiên không thành công |
---|---|
Phiên bản PHP: | 5+ |
Ví dụ - Phong cách thủ tục
Thực hiện nhiều truy vấn đối với cơ sở dữ liệu:
<?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";
// Execute multi query
if (mysqli_multi_query($con, $sql)) {
do {
// Store first result set
if ($result = mysqli_store_result($con)) {
while ($row = mysqli_fetch_row($result)) {
printf("%s\n", $row[0]);
}
mysqli_free_result($result);
}
// if there are more result-sets, the print a
divider
if (mysqli_more_results($con)) {
printf("-------------\n");
}
//Prepare next result set
} while (mysqli_next_result($con));
}
mysqli_close($con);
?>
❮ Tham khảo PHP MySQLi