What are best practices for debugging PHP scripts that involve database dependencies?

When debugging PHP scripts that involve database dependencies, it is important to first check the database connection and ensure that the query is being executed correctly. You can use error handling techniques such as try-catch blocks to catch any exceptions that may occur during database operations. Additionally, logging errors to a file or outputting them to the browser can help in identifying and fixing issues.

<?php
// Establish a database connection
$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);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

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