What are the advantages of using PDO over mysql_connect for database connections in PHP?

Using PDO over mysql_connect in PHP offers several advantages such as support for multiple database systems, prepared statements to prevent SQL injection attacks, and object-oriented approach for database interactions. PDO also provides better error handling and easier debugging capabilities compared to the mysql_connect function.

// Using PDO for database connection in PHP
$host = 'localhost';
$dbname = 'database';
$username = 'username';
$password = 'password';

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