Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQLi error handling

Is it possible to specify that MySQLi sends any errors and warnings to the PHP default 'error_log' directive? I can't seem to find any error options for the class specification, and I don't wish to handle errors manually like so:

if ($result = $mysqli->query("...")) {  }
else
    handle $mysqli->error;
like image 432
Spoonface Avatar asked May 28 '10 20:05

Spoonface


People also ask

How can I see MySQLi errors?

Just simply add or die(mysqli_error($db)); at the end of your query, this will print the mysqli error.

What is Mysqli_error?

Definition and Usage The error / mysqli_error() function returns the last error description for the most recent function call, if any.

How can I get MySQL error code in PHP?

Description ¶ Instead, use mysql_error() to retrieve the error text. Note that this function only returns the error text from the most recently executed MySQL function (not including mysql_error() and mysql_errno()), so if you want to use it, make sure you check the value before calling another MySQL function.

Is it better to use PDO or MySQLi?

The main advantage of PDO over MySQLi is in the database support. PDO supports 12 different database types, in opposition to MySQLi, which supports MySQL only. When you have to switch your project to use another database, PDO makes the process simpler.


1 Answers

Well, one way would be to override the class:

class myMySQLi extends MySQLi {

    public function query($query, $resultmode = MYSQLI_STORE_RESULT) {
        $res = parent::query($query, $resultmode);
        if (!$res) {
            //handle error
        }
        return $res;
    }
}

Then just use as normal, except instead of creating an connection via new MySQLi(), use new myMySQLi(). Other than the error handling, it'll run just the same. I do this quite often, to throw exceptions on errors and to add additional functionality to MySQLi...

like image 127
ircmaxell Avatar answered Oct 05 '22 14:10

ircmaxell