mysqli->error: Is it for the last query only, or for the last error from the query group?

By : Eli
Source: Stackoverflow.com
Question!

I am new to mysqli, and trying to confirm that if I so something like the below, the errno will be set to the last error, if any, and not the error of the last query.

Is this a decent practice or should I be checking for the error in between every query?

Thanks!

$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
}
By : Eli


Answers

IMO the best way and 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;
    }
}


No you have to check in between every query because it will always give you error for last query only... So if your first query failed and last execute properly then you will not get error... so check after all query one by one not at last...

By : Dev


mysqli_errno — Returns the error code for the most recent function call.

By : Ray


This video can help you solving your question :)
By: admin