Try / catch in mysqli

If you need to catch exceptions on mysqli extension by use try/catch block, try this code (switch on exception mode instead of classic error reporting):

// Method 1:
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_STRICT | MYSQLI_REPORT_ERROR;

// OR Method 2:
mysqli_report(MYSQLI_REPORT_STRICT | MYSQLI_REPORT_ALL);

try {
    $db = new mysqli("host", "user", "password", "database");
} catch (mysqli_sql_exception $e) {
    ...
}

mysqli_sql_exception mysqli_driver


In the first section of code when you use the if statement, you are checking to see if that one condition is true and then outputting your message.

A try catch block essentially works like this

try{
   //place code here that could potentially throw an exception
}
catch(Exception $e)
{
  //We will catch ANY exception that the try block will throw

}

So you see that while your if statement is checking for a condition that you are anticipating, the try catch block will detect anything that goes wrong, even those things that you don't anticipate. Therefore, when debugging you can alter the code in the catch block to deal with exceptions as you see fit

See the PHP docs for more information about exceptions http://php.net/manual/en/language.exceptions.php