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

When choosing between PDO and MySQLi for database connections in PHP, PDO offers several advantages over MySQLi. PDO provides a consistent interface for accessing different types of databases, allowing for easier database portability. Additionally, PDO supports prepared statements, which help prevent SQL injection attacks. PDO also offers support for transactions, making it easier to manage database operations that require multiple queries.

// Using PDO for database connection 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 to database successfully";
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}