title: mysqli uses much more memory than mysql, exhausts memory_limit
body: <p>I am trying to update an old app that is currently still using <code>mysql</code> functions. Unfortunately, with <code>mysqli</code>, the app runs out of memory in cases where <code>mysql</code> never did (and, honestly, it shouldn't). With <code>mysql</code>, the process gets up to maybe 50 MB, which suggests it's allocating 8-15 MB on top of the idle set size. With <code>mysqli</code>, it exhausts the limit (128) and even hit 256 MB without blinking (just loading the index page). Something isn't right. I am receiving this error when I switch to <code>mysqli</code>:</p>
  
  <blockquote>
    <p>Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 9072253 bytes)</p>
  </blockquote>
  
  <p>The "tried to allocate" amount of bytes changes every time, it's not constant. The app does have an abstraction class, so I started by gutting that and replacing the calls with a <code>mysqli</code> instance (OOP, not procedural). Rewriting all the queries will take a long time and isn't feasible resource-wise right now. I do have <code>mysqlnd</code> installed. This is currently on PHP 5.6.30.</p>
  
  <p>The code has changed a lot through troubleshooting, but here is one incarnation of the <code>query</code> method:</p>
  
  <pre><code>$result = $connection-&gt;query($sql);
  $data = Array();
  $i = 0;
  while ($r = $result-&gt;fetch_assoc())
      $data[$i++] = $r;
  
  $ret = new stdClass();
  $ret -&gt;row = isset($data[0]) ? $data[0] : Array();
  $ret -&gt;rows = $data;
  $ret -&gt;num_rows = $i;
  
  $result-&gt;free();
  unset($data);
  return $ret ;
  </code></pre>
  
  <p>I've tried using <code>MYSQLI_USE_RESULT</code> and a few different ways of iterating/gathering the query results, like <code>fetch_all</code>, reference assignment, no <code>while</code> loop, but none of it helped.</p>
  
  <p>My next step would probably be to try a PDO instance instead...</p>