我使用mysqli commit语句插入了大量记录,使用来自http://www.php.net/manual/en/mysqli.commit.php#88857的代码.然后我使用:$ mysqli-> affected_rows检查受影响的行,但即使已插入所有记录,我也会得到零影响的行.
如何检查提交失败并检索错误?谢谢
你可以这样做:
mysqli_autocommit($dbconn, FALSE);
$errors = array();
if (!$mysqli->query(/* some SQL query */)) {
$errors[] = $mysqli->error;
}
// ... more queries like the above
if(count($errors) === 0) {
$mysqli->commit()
} else {
$mysqli->rollback();
print_r($errors);
}
Run Code Online (Sandbox Code Playgroud)
当查询出错时,它会将错误添加到$ errors数组中,这样您就会知道出了什么问题.您还可以添加带有查询标识符的键,以便了解哪个查询出错.
为了更好地处理,您可以为此编写一个UnitOfWork类:
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; // return true on success
}
}
Run Code Online (Sandbox Code Playgroud)
你可以像使用它一样
$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());
}
Run Code Online (Sandbox Code Playgroud)