Is there a more efficient way to handle memory consumption in PHP when dealing with large result sets from a database query?

When dealing with large result sets from a database query in PHP, memory consumption can be a concern. One efficient way to handle this is to fetch rows one at a time instead of fetching the entire result set into memory at once. This can be achieved by using a while loop to iterate over the result set and process each row individually.

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

// Prepare and execute the query
$stmt = $pdo->query('SELECT * FROM mytable');

// Fetch and process rows one at a time
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    // Process the row here
    // Example: echo $row['column_name'];
}

// Close the connection
$pdo = null;