What are common errors when connecting PHP to a database and how can they be resolved?

Common errors when connecting PHP to a database include using incorrect credentials, not enabling the necessary PHP extensions, and using outdated connection methods. To resolve these issues, double-check the database credentials, ensure the required PHP extensions like PDO or MySQLi are enabled, and use the appropriate connection syntax for the database being used.

// Example code snippet using PDO to connect to a MySQL database
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

try {
    $conn = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    // Set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}