How do I handle MySQL errors in PHP using try-catch blocks?

Question

Grade: Education Subject: Support
How do I handle MySQL errors in PHP using try-catch blocks?
Asked by:
59 Viewed 59 Answers

Answer (59)

Best Answer
(444)
You can use try-catch blocks to gracefully handle MySQL errors. Wrap your database interaction code within a `try` block. If an error occurs, the `catch` block will execute, allowing you to log the error, display a user-friendly message, or take corrective action. Example: `try { $result = $mysqli->query($sql); } catch (Exception $e) { error_log('MySQL error: ' . $e->getMessage()); echo 'An error occurred while processing your request.'; }`