What are the best practices for error handling and debugging in PHP when working with database queries?

When working with database queries in PHP, it is important to implement proper error handling and debugging practices to ensure smooth execution of your code. To handle errors effectively, you can use try-catch blocks to catch exceptions thrown by database operations and display meaningful error messages. Additionally, enabling error reporting and logging can help in identifying and resolving issues during development and testing.

<?php

// Set error reporting level to display all errors
error_reporting(E_ALL);

// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Perform database query
    $stmt = $conn->prepare("SELECT * FROM users");
    $stmt->execute();

    // Fetch results
    $results = $stmt->fetchAll();

    // Output results
    foreach ($results as $row) {
        echo $row['username'] . "<br>";
    }

} catch (PDOException $e) {
    // Display error message
    echo "Error: " . $e->getMessage();
}

// Close database connection
$conn = null;

?>