What are the best practices for establishing a connection to a MySQL database in PHP?

Establishing a connection to a MySQL database in PHP involves using the mysqli or PDO extension to connect to the database server, providing the necessary credentials such as hostname, username, password, and database name. It is important to handle connection errors gracefully and securely by using try-catch blocks and ensuring that sensitive information is not exposed in the code.

// Using mysqli extension
$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";

// Using PDO extension
$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch(PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}