What are the best practices for establishing a database connection in PHP, such as using PDO?

Establishing a database connection in PHP using PDO is considered a best practice as it provides a secure and efficient way to interact with databases. To establish a connection, you need to create a PDO object with the appropriate database credentials such as the database server, username, password, and database name.

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

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();
}