What are some recommended error handling techniques for MySQL queries in PHP?
When executing MySQL queries in PHP, it is important to implement error handling techniques to gracefully handle any potential issues that may arise during the query execution. One recommended technique is to use the try-catch block to catch any exceptions thrown by the MySQL query execution and handle them accordingly. Additionally, you can use the mysqli_error() function to retrieve the error message generated by the most recent MySQL operation.
// 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
try {
$result = $mysqli->query("SELECT * FROM table");
if (!$result) {
throw new Exception($mysqli->error);
}
// Process query results
while ($row = $result->fetch_assoc()) {
// Do something with the data
}
// Free result set
$result->free();
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
// Close MySQL connection
$mysqli->close();