What are the best practices for handling query results in PHP using mysqli or PDO?

When handling query results in PHP using mysqli or PDO, it is important to properly fetch and process the data returned from the database. Best practices include checking for errors, using prepared statements to prevent SQL injection, and properly looping through the result set to access the data.

// Using PDO to handle query results
try {
    $pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
    $stmt = $pdo->prepare("SELECT * FROM mytable");
    $stmt->execute();

    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        // Process each row of data here
        echo $row['column_name'] . "<br>";
    }
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
}