How can you ensure proper error handling in PHP when executing database queries?

Proper error handling in PHP when executing database queries can be ensured by using try-catch blocks to catch any exceptions that may occur during the query execution. Within the catch block, you can log the error message or handle it appropriately. Additionally, you can use functions like mysqli_error() or PDO::errorInfo() to retrieve detailed error information.

try {
    // Connect to the database
    $conn = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
    
    // Execute the query
    $stmt = $conn->query("SELECT * FROM myTable");
    
    // Fetch the results
    $results = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    // Handle any database query errors
    echo "Error: " . $e->getMessage();
}