What are some best practices for testing PHP scripts to ensure they can successfully connect to a database?

When testing PHP scripts to ensure they can successfully connect to a database, it is important to use try-catch blocks to handle any potential connection errors gracefully. Additionally, using the correct database credentials and ensuring that the necessary PHP extensions are enabled are crucial steps in testing database connections.

<?php
$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();
}
?>