What are the potential errors that can occur when connecting to a MySQL database using PHP and how can they be handled?

One potential error when connecting to a MySQL database using PHP is a connection failure due to incorrect credentials or server issues. This can be handled by using try-catch blocks to catch and handle any exceptions that may occur during the connection process.

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>