What are the best practices for handling MySQL errors and displaying meaningful error messages in PHP scripts?
When working with MySQL in PHP scripts, it is important to handle errors gracefully and display meaningful error messages to the user. This can help troubleshoot issues and provide a better user experience. One way to achieve this is by using try-catch blocks to catch exceptions thrown by MySQL queries and then displaying the error message to the user.
<?php
// Connect to MySQL database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Perform MySQL query
try {
$result = $conn->query("SELECT * FROM table");
if ($result === false) {
throw new Exception($conn->error);
}
// Process query results
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Close MySQL connection
$conn->close();
?>