php – How to create Exceptions to handle statement with MySQLi

Question:

I'm migrating from PDO to Mysqli and when I was doing some operation with the database, the verification block was like this:

$query = $db->prepare("ppapapa sql sql");

try {
        $query -> execute();
        return $query -> fetchAll();

    } catch(PDOException $e) {
        die($e -> getMessage());
    }

How would this error handling be with MySQLi?

Answer:

You need to enable exceptions with:

mysqli_report(MYSQLI_REPORT_ALL);

The use:

mysqli_report(MYSQLI_REPORT_STRICT);

Then you can use normally:

$query = $db->prepare("ppapapa sql sql");
try {
    $query -> execute();
    return $query -> fetchAll();
} catch(mysqli_sql_exception $e) {
    die($e -> getMessage());
}

mysqli_report() .

If you don't want to do this, you can handle the errors individually:

if (!mysqli->query($insadquery)) die(mysqli->errno . " - " . $mysqli->error);

I put it on GitHub for future reference .

This form is often preferable.

Documentation of all mysqli .

Scroll to Top