What are some best practices for securely connecting to a MySQL database in PHP?

When connecting to a MySQL database in PHP, it is important to ensure that the connection is secure to prevent unauthorized access or data breaches. One best practice is to use prepared statements to prevent SQL injection attacks. Additionally, using a secure password and limiting the privileges of the database user can help enhance security.

// Securely connect to a MySQL database using PDO with prepared statements

$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Error: " . $e->getMessage());
}