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

When it comes to database connections in PHP, PDO (PHP Data Objects) is often preferred over mysqli due to its flexibility, security, and support for multiple database systems. PDO allows for the use of prepared statements, which helps prevent SQL injection attacks. Additionally, PDO supports multiple database systems, making it easier to switch between databases without changing your code.

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