What are the best practices for error handling in PHP, specifically when using MySQL queries?
When handling errors in PHP, especially when dealing with MySQL queries, it is important to check for errors after executing the query and handle them appropriately. One common practice is to use the mysqli_error() function to retrieve the error message if the query fails. Additionally, using prepared statements can help prevent SQL injection attacks and make error handling easier.
// Connect to the database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute a query
$query = "SELECT * FROM table";
$result = $mysqli->query($query);
// Check for errors
if (!$result) {
die("Error: " . $mysqli->error);
}
// Process the results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Close the connection
$mysqli->close();