具有Mulitple Update准备的语句的PDO无法执行

时间:2018-10-27 10:15:21

标签: php sql pdo

我正在尝试构造一个PDO多个准备好的语句来更新2个表。

在尝试使代码正常工作时,我遇到了麻烦并遇到各种错误,最新的消息是:SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens

在查看SO时,我发现了执行此操作的各种方法,但是我不知道如何实现它们。

另一个问题是无法使用$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);。我已阅读在线内容,以确保安全性。但是我也了解到,它不适用于Multi Queries PDO(?)。

可以进行多重更新,还是应该使用其他脚本? (我的代码也不受SQL注入的影响吗?)

这是我正在使用的代码:

<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=*', '*', '*');
$conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//$conn->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);


$est_id = $_POST['est_id'];
$known_for = $_POST['known_for'];
$street_address = 'addressToAdd';

$sql = " UPDATE `theList`
 SET `known_for` = :known_for
 WHERE `id` = :est_id
    ";

$sql = " UPDATE `est_address`
  SET `street_address` = :street_address
  WHERE `id` = :est_id
     ";

 $params = array(
    ':est_id' => $est_id,
    ':known_for' => $known_for,
    ':street_address' => $street_address
);


  $statement = $conn->prepare($sql);

  $statement->execute($params);


  $conn = null;        // Disconnect
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>

1 个答案:

答案 0 :(得分:0)

<?php
try {
$conn = new PDO('mysql:host=localhost;dbname=*', '*', '*');
$conn->exec("SET CHARACTER SET utf8");      // Sets encoding UTF-8
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$est_id = $_POST['est_id'];
$known_for = $_POST['known_for'];
$street_address = 'addressToAdd';

$sqlKnown = "UPDATE `theList` SET `known_for` = :known_for WHERE `id` = :est_id";
$stKnown = $conn->prepare( $sqlKnown );
$stKnown->execute([
  ':est_id' => $est_id,
  ':known_for' => $known_for,
]);

$sqlStreet = "UPDATE `est_address` SET `street_address` = :street_address WHERE `id` = :est_id";
$stStreet = $conn->prepare( $sqlStreet );
$stStreet->execute([
  ':est_id' => $est_id,
  ':street_address' => $street_address
]);

  $conn = null;        // Disconnect
}
catch(PDOException $e) {
  echo $e->getMessage();
}
?>