What best practices should be followed when establishing a MySQL connection in PHP?

When establishing a MySQL connection in PHP, it is important to follow best practices to ensure security and efficiency. This includes using secure connection methods, such as PDO or MySQLi, to prevent SQL injection attacks. Additionally, it is recommended to store database credentials in a separate configuration file outside of the web root for added security.

<?php
// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>