What are some best practices for error-handling when working with MySQL queries in PHP?
When working with MySQL queries in PHP, it is important to implement proper error-handling to catch and handle any potential issues that may arise during query execution. One best practice is to use the mysqli_error() function to retrieve the error message from MySQL and handle it accordingly.
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check for connection errors
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Execute MySQL query
$result = $mysqli->query("SELECT * FROM table");
// Check for query execution errors
if (!$result) {
die("Query failed: " . $mysqli->error);
}
// Process query results
while ($row = $result->fetch_assoc()) {
// Process each row
}
// Close connection
$mysqli->close();