In terms of security and performance, what are the advantages of using PDO over mysqli for database operations in PHP?

Using PDO over mysqli for database operations in PHP provides advantages in terms of security and performance. PDO offers a more secure way to interact with databases by supporting parameterized queries, which helps prevent SQL injection attacks. Additionally, PDO allows for database abstraction, making it easier to switch between different database systems without changing the code. In terms of performance, PDO is slightly faster than mysqli due to its use of prepared statements.

// Using PDO for database operations 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);
    
    // Example query using prepared statement
    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
    $stmt->execute(['id' => 1]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    // Do something with the result
    print_r($result);
    
} catch(PDOException $e) {
    echo 'Error: ' . $e->getMessage();
}