What are some best practices for handling errors in PHP when working with MySQL queries?
When working with MySQL queries in PHP, it is important to handle errors properly to ensure the stability and security of your application. One best practice is to use try-catch blocks to catch any exceptions that may occur during the execution of the query. Additionally, you can use the mysqli_error() function to retrieve detailed error messages from MySQL and handle them accordingly.
<?php
// Establish a connection to the database
$connection = mysqli_connect("localhost", "username", "password", "database");
// Check for connection errors
if (!$connection) {
die("Connection failed: " . mysqli_connect_error());
}
// Execute a MySQL query
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);
// Check for query execution errors
if (!$result) {
echo "Error: " . mysqli_error($connection);
}
// Close the connection
mysqli_close($connection);
?>