Try / catch in MySQL

I am following the OOP mysqli course. When connecting to the database, they use the following script:

$db = new mysqli("host", "user", "password", "database");
if ($db->connect_error){
    $error = $db->connect_error;
    echo("Not connected: " . $error);
}

      

They later call the database connection file with a try / catch block:

try {
    require_once "connection.php";
}catch (Exception $e){
    $error = $e->getMessage();
    echo $error;
}

      

Is the possible connection error handled by the connection file immediately after the connection attempt? Is the try / catch block mostly the same? Or is the try / catch block looking for another type of error?

UPDATE: Just to clarify by reading some of the answers. When I just do this:

try {
    $db = new mysqli("host", "user", "password", "database");
}catch (Exception $e){
    $error = $e->getMessage();
    echo $error;
}

      

Assuming the database access details are incorrect (for example, the wrong host), I get a PHP warning, but no error output in the catch block. Shouldn't you catch this error?

+5


source to share


3 answers


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

The 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 can see that while the if statement checks for the condition you expect, the try catch block detects everything that goes wrong, even the things that you don't expect. Therefore, when debugging, you can modify the code in the catch block to deal with the exceptions you see fit

For more information on exceptions see the PHP docs http://php.net/manual/en/language.exceptions.php

0


source


If you need to catch exceptions for mysqli extension using try / catch block, try this code (enable 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

+4


source


What is different from $db->connect_error

and , you ask try/catch

?

$db->connect_error

mostly for errors we already knew (username is incorrect, etc.)

and try/catch

refers to the system level after an error occurs,

PHP will look for the closest try / catch block,

once it catches something, PHP will still continue as nothing happened before,

but if you don't have a block try/catch

and set_exception_handler()

also,

PHP will just stop at the error.

-1


source







All Articles