I'm following an 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);
}
Later though, they call the database connection file with a try / catch block:
try {
require_once "connection.php";
}catch (Exception $e){
$error = $e->getMessage();
echo $error;
}
Isn't a possible connection error being handled by the connection file immediately after trying to connect? Is the try / catch block basically doing the same thing? Or is the try / catch block looking for a different type of error?
UPDATE: Just to clarify, after 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 that the database access data is wrong (for example a wrong host), I get a PHP warning but not the error output in the catch block. Shouldn't the catch detect this error?
The primary method of handling exceptions in PHP is the try-catch. In a nutshell, the try-catch is a code block that can be used to deal with thrown exceptions without interrupting program execution. In other words, you can "try" to execute a block of code, and "catch" any PHP exceptions that are thrown.
// 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) { ... } Save this answer.
The mysqli_error() function is used to return the error in the most recent MySQL function call that failed. If there are multiple MySQL function calls, the error in the last statement is the one that is pointed out by the function.
Return Values ¶ For successful queries which produce a result set, such as SELECT, SHOW, DESCRIBE or EXPLAIN , mysqli_query() will return a mysqli_result object. For other successful queries, mysqli_query() will return true .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With