What are the advantages of using the PDO class over MySQLi in PHP?

When working with databases in PHP, using the PDO class over MySQLi offers several advantages. PDO supports multiple database drivers, making it more versatile and easier to switch between different databases. PDO also provides a more secure way to interact with databases by using prepared statements, which helps prevent SQL injection attacks. Additionally, PDO has a more consistent and object-oriented approach to database operations, making it easier to work with and maintain code.

// Connect to a MySQL 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);
    echo "Connected successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}