What are the best practices for connecting to a MySQL database in PHP and handling errors?

When connecting to a MySQL database in PHP, it is important to handle errors properly to ensure the stability and security of your application. One best practice is to use try-catch blocks to catch any potential exceptions that may occur during the connection process. Additionally, it is recommended to use prepared statements to prevent SQL injection attacks.

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