What is the recommended approach for connecting to MySQL databases in PHP?

The recommended approach for connecting to MySQL databases in PHP is to use the PDO (PHP Data Objects) extension. PDO provides a consistent interface for accessing databases, including MySQL, and offers features like prepared statements to help prevent SQL injection attacks.

// Database connection parameters
$host = 'localhost';
$dbname = 'database_name';
$username = 'username';
$password = 'password';

// Create a PDO 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());
}