What are the advantages of using PDO over mysqli for database connectivity in PHP?

When choosing between PDO and mysqli for database connectivity in PHP, PDO offers several advantages. PDO supports multiple database drivers, making it more flexible for working with different types of databases. Additionally, PDO provides a more secure way to interact with databases by using prepared statements, which help prevent SQL injection attacks. Lastly, PDO is object-oriented, making it easier to work with and maintain code compared to the procedural style of mysqli.

// Using PDO for database connectivity in PHP
$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();
}