How can one establish a database connection in PHP to retrieve data from a server and display it on an HTML page?

To establish a database connection in PHP to retrieve data from a server and display it on an HTML page, you can use the PDO (PHP Data Objects) extension. This allows you to connect to various database management systems like MySQL, PostgreSQL, SQLite, etc. You will need to provide the database credentials such as host, username, password, and database name to establish the connection.

<?php
// Database credentials
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

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