In PHP, this can be done by mysqli_multi_query() The function executes multiple SQL statements in a single call.
Here is an example code snippet:
<?php
// 定义 MySQL 数据库连接参数
$host = "localhost";
$user = "root";
$password = "password";
$dbname = "mydatabase";
// 创建 MySQL 数据库连接
$conn = mysqli_connect($host, $user, $password, $dbname);
// 检查连接是否成功
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
// 要执行的 SQL 语句,多条语句以分号隔开
$sql = "INSERT INTO mytable (id, name, age) VALUES (1, 'Alice', 18);"
. "INSERT INTO mytable (id, name, age) VALUES (2, 'Bob', 20);"
. "INSERT INTO mytable (id, name, age) VALUES (3, 'Charlie', 22);";
// 执行多条 SQL 语句
if (mysqli_multi_query($conn, $sql)) {
echo "执行成功";
} else {
echo "执行失败: " . mysqli_error($conn);
}
// 关闭 MySQL 数据库连接
mysqli_close($conn);
?>In this example code, a MySQL database connection is first established, followed by the definition of the SQL statements to be executed—these statements are separated by semicolons. Finally, the code is used. mysqli_multi_query() The function executes multiple SQL statements in a single call.
Please note that,mysqli_multi_query() When a function executes multiple SQL statements, if any single statement fails to execute, all subsequent statements will also be terminated. Therefore, it is essential to carefully examine and validate the SQL statements before invoking this function to ensure their correctness and reliability.