What are the advantages of using PDO over traditional MySQL functions for database connectivity in PHP scripts?

Using PDO over traditional MySQL functions in PHP scripts offers several advantages, such as improved security through the use of prepared statements to prevent SQL injection attacks, database abstraction that allows for easier switching between different database systems, and support for transactions for better error handling and data integrity.

// 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) {
    die('Connection failed: ' . $e->getMessage());
}