Skip to main content
6 of 24
added 57 characters in body; added 92 characters in body; deleted 5 characters in body

MySQLi_Recordset: blending SPL and Statement/Query results

Additional post tags should be: mysqli spl, but I'm too new on CR.

I've made a SPL-based class named MySQLi_Recordset that wraps both MySQLi_STMT and MySQLi_Result objects and allows treating either as a 3-dimensional array. It requires PHP5.3+.

The code is roughly 200 lines long, so instead of making a giant post, here's a pastebin link... http://pastebin.com/LUe4j9DM

This class allows accessing result rows by array key (echo $recorset[295]['title'];) or by foreach loops (foreach ($recordset as $rec) {echo $rec['title'];}). Objects are created by passing in an sql query statement. For handling prepared statements, simply pass in additional arguments as the prepared binding parameters. In those cases, there is a behind-the-scenes bind_param going on to generate the MySQLi_STMT object to be wrapped, but that part isn't included here. So for the purposes of this post, pretend it's magic.

For example to automatically handle the query as a prepared statement:

$recordset = new MySQLi_Recordset("SELECT * FROM tblComments WHERE(parentBlogID = ?)", 2);
if (count($recordset) > 0) {
    foreach ($recordset as $record)
        echo $record['commentText'] . '<br>';
    }
else echo "No records returned.";

Here's some speed tests iterating over 10000 records from a localhost table with 6 columns. This test was done with prepared statement results either wrapped in MySQLi_Recordset or not...

With MySQLi_Recordset...

  • foreach($MySQLi_Recordset as $rec) {$x = $rec;} ...
    0.10268998146057 ms
  • for ($i = 0, $count = count($MySQLi_Recordset); $i < $count; $i++) {$x = $MySQLi_Recordset[$i];} ...
    0.056336879730225 ms
  • for ($i = 0, $count = count($MySQLi_Recordset); $i < $count; $i++) {$x = $MySQLi_Recordset->fetchRow($i);} ...
    0.034775972366333 ms
  • $i=0; while ($x = $recordset[$i]) {if (!isset($recordset[$i])) break; $i++;} ... 0.06541895866394 ms

Without MySQLi_Recordset, but still using the "bind to array" technique and pre-storing results...

  • for ($i=0, $count=$MySQLI_STMT->num_rows; $i < $count; $i++)) {$MySQLI_STMT->fetch(); $x = $bind_row;} ...
    0.040991067886353 ms
  • while ($MySQLI_STMT->fetch()) {$x = $bind_row;} ...
    0.0096209049224854 ms ms

I'm pretty bummed about the slow foreach loop over my MySQLi_Recordset object, by the slow seek and fetch speeds within MySQLi_Recordset, and by the fact that nothing can even compare to while ($MySQLI_STMT->fetch()) {}.I'd like for this to work, especially since it allows exchanging this class out for regular 3-dimensional arrays of result dumps easily and avoiding duplication of binding code on every statement throughout an application. Any suggestions or criticisms?