PHP to display database query errors
try {
// Execute the query
$result = $mysqli->query($sql);
// Check for errors
if (!$result) {
throw new Exception('Error executing the query: ' . $mysqli->error);
}
// Process the results
} catch (Exception $e) {
// Handle the error gracefully
echo 'An error occurred: ' . $e->getMessage();
}
This code demonstrates how to handle database query errors in PHP using try-catch blocks.
-
Execute the query using the
mysqli_query()
function. -
Check for errors using the
!$result
condition. If the query fails, it will return FALSE, indicating an error. -
If an error occurs, throw an exception using the
throw new Exception()
statement. The exception message should include the error message retrieved from themysqli_error()
function. -
Catch the exception using a
catch (Exception $e)
block. Inside the catch block, handle the error by logging it, displaying it to the user, or taking other appropriate actions. -
To implement this effectively, ensure that you handle all potential errors that may occur during query execution. Customize the error handling based on your application’s requirements.