How to properly handle errors with transactions and prepared statements when using mysqli?
Snippet:
<?php
$conn = require_once 'dbconn.php';
$conn->autocommit(FALSE);
$stmt_ins_option = $conn->prepare('INSERT INTO options(option_name) VALUES(?)');
$option_name = 'foo';
$stmt_ins_option->bind_param('s', $option_name);
$stmt_ins_option->execute();
$conn->commit();
if($conn->errno) {
$conn->rollback();
echo $conn->error;
}
It won’t add it a second time because there’s a UNIQUE constraint on that column.
However the script won’t report any error either.
What am I missing?
executereturns false on failure, so you may want to check it before committing. Also, rolling back in your code has no effect because you committed transaction previously. I’d write something like