What best practices should be followed when connecting to a MySQL database in PHP?

When connecting to a MySQL database in PHP, it is important to follow best practices to ensure security and efficiency. This includes using prepared statements to prevent SQL injection attacks, using secure connection methods, and properly sanitizing user input.

// Connect to MySQL database using PDO with prepared statements
$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);
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}