MySQLi error handling [duplicate]
Asked Answered
C

2

6

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;
Cantlon answered 28/5, 2010 at 20:5 Comment(0)
M
3

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...

Mistakable answered 28/5, 2010 at 20:14 Comment(1)
hi there thanks for your reply. I suppose I could do that if it's the only option, but it seems odd to me that an error generated by the mysqli ctor can be logged to the default error_log, but any errors that occur while using the mysqli object have to be manually handled!Cantlon
A
1

Of course, it is possible. All you have to do is enable automatic error reporting and tell PHP to log all errors into a file.

Before you open a connection using mysqli you should ensure that you have these two settings enabled:

ini_set("log_errors", 1); // this can be set in INI file too, together with error_log path
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = new mysqli('localhost', /** ... */);

You don't need to check for mysqli errors manually anymore and all errors will be logged to a file.

Aurilia answered 14/2, 2021 at 14:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.