PHP: how are query results stored in mysqli_result

Viewed 2081

When I made a query to the database and retrieve the results in mysqli_result, the memory usage is extremely small. However, when I fetch all the rows in the query results in to an associative array, the memory usage becomes extremely high.

<?php
    require_once("../config.php"); //db connection config
    $db = new mysqli(DB_HOST,DB_USER,DB_PASSWORD,DB_DBASE);

    $query ="select * from table_name";
    if($r = $db->query($query)){
    echo "MEMORY USAGE before :  ". memory_get_usage()."<br><br>";
    $rows = array();
    while($row = $r->fetch_assoc()){

        $rows[]= $row;
    }
    echo "MEMORY USAGE after :  ". memory_get_usage()."<br><br>";


    //before: 660880
    //after:  114655768
    // # of records: around 30 thousands
?>

It makes sense to me that storing this many results is very memory consuming, but I'm just wondering how come mysqli_result is so small. It can't be that the results are queried to the dbase every time fetch_assoc is called. So then where are the results stored in the memory.

2 Answers
Related