What are best practices for error handling in PHP database queries?
When handling errors in PHP database queries, it is important to check for errors after executing the query and handle them appropriately. One common practice is to use try-catch blocks to catch exceptions thrown by the database connection. Additionally, using functions like mysqli_error() or PDO::errorInfo() can provide more detailed error messages for debugging.
try {
// Perform database query
$result = $pdo->query("SELECT * FROM users");
// Check for errors
if(!$result) {
throw new Exception($pdo->errorInfo()[2]);
}
// Process query results
foreach($result as $row) {
// Do something with the data
}
} catch(Exception $e) {
// Handle the error
echo "Error: " . $e->getMessage();
}