All I want to know is if you can use mysqli's prepare, execute, and rollback together?
$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();}
Can you do this? Let's assume that the above code has a loop and or the variables get new data in them.
Best way to handle this is with exceptions (as always, darn PHP error/warning stuff). Simply because our commit() call may fail too. Note that finally is only available in newer PHP versions.
<?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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With