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

When connecting to a MySQL database in PHP, it is important to follow best practices to ensure secure and efficient communication. One common best practice is to use PDO (PHP Data Objects) to connect to the database, as it provides a secure and flexible way to interact with the database. Additionally, using prepared statements can help prevent SQL injection attacks by separating SQL logic from user input.

// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

try {
    // Create a new PDO instance
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    
    // Set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}