What are the potential benefits of switching from mysql to PDO for database connections in PHP?

Switching from mysql to PDO for database connections in PHP can bring several benefits, such as improved security through prepared statements and parameterized queries, support for multiple database types, and better error handling capabilities. PDO also provides a more consistent and object-oriented approach to working with databases in PHP.

// Using PDO for database connection
$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);
    
    // Perform database operations using $pdo object
} catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
}