准备好的语句可以在 php 中包含多个查询吗

Can a prepared statement hold multiple queries in php

最近,我正试图保护我的查询免受 SQL 注入。我已经开始将我用来进行查询的字符串转换为语句,但是,我制作的一些字符串需要同时进行多个查询,因为一个插入的 id 将作为外键添加到下一个,我将通过使用 LAST_INSERT_ID() 获得,因此我需要它们一个接一个地执行。

一个语句可以同时包含多个查询并一次执行吗?

顺便说一句,这是之前的代码。

$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`) 
            VALUES ('{$firstName}', '{$lastName}', '{$phone}', '{$cpf}');";
$sql .= "SELECT LAST_INSERT_ID() INTO @mysql_variable_here;";
$sql .= "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
            VALUES ('{$email}','{$password}', 1, @mysql_variable_here, '{$created}', {$role}" . $restaurantValue . " );"; 
$sql .= "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
            VALUES ('{$number}', '{$street}', '{$city}', '{$stateCode}', '{$zip}', '{$district}', 'BR', '{$created}', @mysql_variable_here);";

$result = $conn->multi_query($sql);```

您不能在 prepared query:

中执行多个语句

SQL syntax for prepared statements does not support multi-statements (that is, multiple statements within a single string separated by ; characters)

因此您需要分别准备和执行每个查询,使用 mysqli_stmt::insert_id 为第二个和第三个查询获取适当的 id 值:

$sql = "INSERT INTO `user_info`(`first_name`, `last_name`, `phone`, `cpf`) 
            VALUES (?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssss', $firstName, $lastName, $phone, $cpf);
$stmt->execute();
$insert_id = $stmt->insert_id;
$stmt->close();

$sql = "INSERT INTO `{$table}`(`email`, `password`, `active`,`user_info_id`, `created`, `role_id`" . $restaurantInsert . ")
            VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $conn->prepare($sql);
$stmt->bind_param('ssiisss', $email, $password, 1, $insert_id, $created, $role, $restaurantValue);
$stmt->execute();
$stmt->close();

$sql = "INSERT INTO `address`(number, street, city, state, zip, district, country, created, user_info_id)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
$stmt = $conn->prepare($sql);
$country = 'BR';
$stmt->bind_param('sssssssi', $number, $street, $city, $stateCode, $zip, $district, $country, $created, $insert_id);
$stmt->execute();
$stmt->close();

请注意,我不是 100% 确定您要通过 <code>role_id" . $restaurantInsert . " 实现的目标,您可能需要编辑第二个适当查询以使用它。