You can do something like this:
mysqli_autocommit($dbconn, FALSE); $errors = array(); if (!$mysqli->query()) { $errors[] = $mysqli->error; }
When the request goes wrong, it will add an error to the $ errors array so you know what went wrong. You can also add keys with identifiers for requests so that you know which request went wrong.
For better handling, you can write the UnitOfWork class:
class UnitOfWork { protected $_db; protected $_errors; protected $_queries; public function __construct($db) { $this->_db = $db; $this->_errors = array(); $this->_queries = array(); } public function addQuery($id, $sql) { $this->_queries[$id] = $sql; return $this; } public function getErrors() { return $this->_errors; } public function try() { $this->_db->autocommit($this->_db, FALSE); foreach($this->_queries as $id => $query) { if ($this->_db->query($query) === FALSE) { $this->_errors[$id] = $this->_db->error; } } $hasErrors = count($this->_errors); ($hasErrors) ? $this->_db->rollback() : $this->_db->commit(); $this->_db->autocommit($this->_db, TRUE); return !$hasErrors;
and you can use it as
$unit = new UnitOfWork($mysqli); $unit->addQuery('foo', 'SELECT foo FROM somewhere') ->addQuery('bar', 'SELECT bar FROM somewhereElse') ->addQuery('baz', 'SELECT baz WITH brokenQuery'); if($unit->try() === FALSE) { print_r($unit->getErrors()); }
source share