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();
?>
Related Questions
- How can PHP be integrated with MySQL to optimize server performance and resource utilization?
- How can PHP be used to create an admin center for a website, similar to popular CMS platforms?
- In what scenarios would it be more appropriate to use an API or database extraction instead of file_get_contents for reading content in PHP?