How does PDO differ from MySQLi in terms of handling result sets and prepared statements in PHP?

PDO and MySQLi both provide ways to interact with databases in PHP, but they differ in how they handle result sets and prepared statements. PDO allows for a more consistent interface for different database systems, making it easier to switch between databases. Additionally, PDO supports named parameters in prepared statements, which can make the code more readable and easier to maintain.

// Using PDO to handle result sets and prepared statements
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    
    // Handling result sets
    $stmt = $pdo->query("SELECT * FROM users");
    while ($row = $stmt->fetch()) {
        // Process each row
    }

    // Using prepared statements
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
    $stmt->execute(['id' => 1]);
    $result = $stmt->fetch();
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}