What are some best practices for error handling and debugging in PHP scripts, especially when dealing with database queries?

When dealing with database queries in PHP scripts, it is important to implement proper error handling to catch any potential issues that may arise during the execution of the queries. One common practice is to use try-catch blocks to capture any exceptions thrown by the database queries and handle them accordingly. Additionally, enabling error reporting and displaying error messages can help in identifying and resolving any issues that occur during the execution of the script.

// 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);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

// Execute a database query
try {
    $stmt = $conn->prepare("SELECT * FROM table");
    $stmt->execute();
    $result = $stmt->fetchAll();
} catch(PDOException $e) {
    echo "Error executing query: " . $e->getMessage();
}