What are the best practices for handling errors in MySQL queries in PHP, especially when testing code?
When handling errors in MySQL queries in PHP, 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 and log it or display it to the user. 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);
}
// Fetch results
while ($row = $result->fetch_assoc()) {
// Process results
}
// Close connection
$mysqli->close();