What are the advantages of using PDO over mysqli for prepared statements in PHP?

When using prepared statements in PHP, PDO is often preferred over mysqli due to its support for multiple database systems, object-oriented approach, and easier error handling. PDO provides a consistent interface for accessing different database types, making it easier to switch between databases without changing much code. Additionally, PDO allows for named parameters in prepared statements, which can improve code readability and maintainability.

// Using PDO for prepared statements
try {
    $pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password");
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->bindParam(':id', $id, PDO::PARAM_INT);
    $stmt->execute();
    $result = $stmt->fetchAll(PDO::FETCH_ASSOC);
    foreach ($result as $row) {
        // Process the data
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}