6

我只想知道你是否可以同时使用 mysqli 的prepare, execute, and rollback

$m = new mysqli($dbhost,$dbuser,$dbpassword,$dbname);

$m->autocommit(FALSE);
$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
$query_ok = $stmt->execute();

$stmt = $m->prepare("INSERT `table` (`name`,`gender`,`age`) VALUES (?,?,?)");
$stmt->bind_param("ssi", $name, $gender, $age);
if ($query_ok) {$query_ok = $stmt->execute();}

if (!$query_ok) {$m->rollback();} else {$m->commit();}

你能做这个吗?假设上面的代码有一个循环,或者变量在其中获取新数据。

4

1 回答 1

2

处理此问题的最佳方法是处理异常(一如既往,该死的 PHP 错误/警告内容)。仅仅是因为我们的commit()调用也可能失败。请注意,finally仅在较新的 PHP 版本中可用。

<?php

// Transform all errors to exceptions!
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try {
  $connection = new \mysqli($dbhost, $dbuser, $dbpassword, $dbname);
  $connection->autocommit(false);

  $stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");
  $stmt->bind_param("ssi", $name, $gender, $age);
  $stmt->execute();

  // We can simply reuse the prepared statement if it's the same query.
  //$stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?)");

  // We can even reuse the bound parameters.
  //$stmt->bind_param("ssi", $name, $gender, $age);

  // Yet it would be better to write it like this:
  /*
  $stmt = $connection->prepare("INSERT `table` (`name`, `gender`, `age`) VALUES (?, ?, ?), (?, ?, ?)");
  $stmt->bind_param("ssissi", $name, $gender, $age, $name, $gender, $age);
   */

  $stmt->execute();
  $connection->commit();
}
catch (\mysqli_sql_exception $exception) {
  $connection->rollback();
  throw $exception;
}
finally {
  isset($stmt) && $stmt->close();
  $connection->autocommit(true);
}
于 2014-07-05T08:24:10.293 回答