What best practices should be followed for error handling in PHP when dealing with SQL queries?
When dealing with SQL queries in PHP, it is important to implement proper error handling to catch any potential issues that may arise during the execution of the queries. One best practice is to use try-catch blocks to handle exceptions thrown by the database connection or query execution. Additionally, you should always check the return value of query execution functions to ensure that the query was successful.
try {
// Attempt to establish a connection to the database
$conn = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Attempt to execute a SQL query
$stmt = $conn->query("SELECT * FROM mytable");
if ($stmt) {
// Query was successful, process the results
// ...
} else {
// Query failed, handle the error
throw new Exception("Error executing SQL query");
}
} catch (PDOException $e) {
// Handle any PDO exceptions
echo "Connection failed: " . $e->getMessage();
} catch (Exception $e) {
// Handle any other exceptions
echo "Error: " . $e->getMessage();
} finally {
// Close the database connection
$conn = null;
}