What are the recommended methods for error handling in PHP when dealing with SQL queries?
When dealing with SQL queries in PHP, it is recommended to use try-catch blocks to handle errors effectively. By wrapping your SQL query execution code in a try block and catching any potential exceptions in a catch block, you can gracefully handle errors and prevent your application from crashing.
try {
// Connect to the database
$conn = new PDO("mysql:host=localhost;dbname=myDB", $username, $password);
// Prepare and execute the SQL query
$stmt = $conn->prepare("SELECT * FROM users WHERE id = :id");
$stmt->execute(['id' => $userId]);
// Fetch the results
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Close the connection
$conn = null;
} catch (PDOException $e) {
echo "Error: " . $e->getMessage();
}