MySQL Query Iterator

Iterators are for more than just directories. You can also apply them to database queries. In Chapter 3, you saw MySQL’s new mysqli_multi_query( ) function, which is used to send multiple queries at once. However, processing involves a minimum of four functions and a do/while loop. Yikes!

Despite these complexities, the essential action is iteration: in this case, you’re iterating through database results. The iteration requires more steps than a normal query, but in its essence, it’s just iteration.

This is the perfect task to encapsulate inside an Iterator. The MySQLiQueryIterator takes a nasty string of code:

if (mysqli_multi_query($db, $query)) {
        do {
            if ($result = mysqli_store_result($db)) {
                while ($row = mysqli_fetch_row($result)) {
                    print "$row[0]\n";
            }
            mysqli_free_result($result);
        }
    } while (mysqli_next_result($db));
}

and transforms it into something clear and simple:

foreach (new MySQLiQueryIterator($db, $query) as $result) {
        if ($result) {
                while ($row = mysqli_fetch_row($result)) {
                    print "$row[0]\n";
                }
        }
}

Example 6-2 demonstrates the code for MySQLiQueryIterator.

Example 6-2. Implementing a MySQL multi-query iterator

class MySQLiQueryIterator implements Iterator { protected $link; protected $query; protected $key; protected $valid; protected $result; public function _ _construct($link, $query) { $this->link = $link; $this->query = $query; } public function rewind( ) { $this->key = 0; if (mysqli_multi_query($this->link, $this->query)) { $this->result ...

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.