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

When connecting to a local database in PHP, it is important to follow best practices to ensure the security of your application. One way to securely connect to a local database is by using PDO (PHP Data Objects) with prepared statements to prevent SQL injection attacks. Additionally, you should avoid storing database credentials directly in your code and instead use environment variables or a configuration file outside of the web root.

<?php

// Database credentials
$host = 'localhost';
$dbname = 'your_database_name';
$username = 'your_username';
$password = 'your_password';

// Create a PDO connection
try {
    $pdo = new PDO("mysql:host=$host;dbname=$dbname", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Error connecting to the database: " . $e->getMessage());
}

// Use prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();

// Close the connection
$pdo = null;

?>