How can one optimize PHP code to efficiently handle database query results for output?

To optimize PHP code for efficiently handling database query results for output, one should consider using techniques such as limiting the number of columns retrieved, using pagination to limit the number of results displayed at once, and caching query results to reduce database load. Additionally, using proper indexing on database tables and optimizing SQL queries can also improve performance.

// Example of optimizing PHP code for handling database query results efficiently

// Connect to the database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");

// Prepare and execute the query
$stmt = $pdo->prepare("SELECT id, name, email FROM users");
$stmt->execute();

// Fetch results and output data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "ID: " . $row['id'] . "<br>";
    echo "Name: " . $row['name'] . "<br>";
    echo "Email: " . $row['email'] . "<br><br>";
}