Mysqli-> error: is it for the last request only or for the last error from the request group?
I am new to mysqli and am trying to confirm that if I do something like below, errno will be set to the last error, if any, and not the error of the last request.
Is this a decent practice or should I check for an error between each request?
Thank!
$mysqli->autocommit(FALSE);
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
$mysqli->query("INSERT INTO .....");
if ( 0==$mysqli->errno ) {
$mysqli->commit();
} else {
$mysqli->rollback();
// Handle error
}
source to share
No - it reports the error code of the last call to the mysqli function. Zero means there were no errors on the last call to the function. So if one of them doesn't work, you won't know about it by checking only at the end.
In other words, yes, you need to check the error code after each function call. Note that the error is also indicated by the return value $mysqli->query()
. To paraphrase an example from the mysqli_errno doc:
if (!$mysqli->query("INSERT ...")) {
printf("Errorcode: %d\n", $mysqli->errno);
}
source to share
IMO the best way and the easiest way to catch all errors is to extend the mysqli class:
class DBException extends Exception {
}
class DBConnectException extends DBException {
}
class DBQueryException extends DBException {
}
class DB extends MySQLi {
private static $instance = null;
private function __construct() {
parent::__construct('host',
'username',
'passwd',
'dbname');
if ($this->connect_errno) {
throw new DBConnectException($this->connect_error, $this->connect_errno);
}
}
private function __destructor() {
parent::close();
}
private function __clone() {
}
public static function getInstance() {
if (self::$instance == null) {
self::$instance = new self();
}
return self::$instance;
}
public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
$result = parent::query($query, $resultmode);
if (!$result) {
// or do whatever you wanna do when an error occurs
throw new DBQueryException($this->error, $this->errno);
}
return $result;
}
}
source to share