What are the advantages of using PDO for database queries in PHP over deprecated mysql functions?

Using PDO for database queries in PHP is advantageous over deprecated mysql functions because PDO provides a more secure and flexible way to interact with databases. PDO supports multiple database management systems, prepared statements to prevent SQL injection attacks, and object-oriented approach for easier maintenance and readability of code.

// Connect to database using PDO
$dsn = 'mysql:host=localhost;dbname=mydatabase';
$username = 'username';
$password = 'password';

try {
    $pdo = new PDO($dsn, $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}