Skip to content

Instantly share code, notes, and snippets.

@ferdhie
Last active August 24, 2016 05:16
Show Gist options
  • Save ferdhie/490b60638cf290093b04d81df563464d to your computer and use it in GitHub Desktop.
Save ferdhie/490b60638cf290093b04d81df563464d to your computer and use it in GitHub Desktop.
php mysql query iterator
<?php
class QueryIterator implements Iterator
{
private $position = 0;
private $rows=array();
private $result = NULL;
public function __construct($sql)
{
$this->sql = $sql;
$this->result = mysql_query($this->sql);
}
function rewind()
{
$this->position = 0;
}
function current()
{
return $this->rows[$this->position];
}
function key()
{
return $this->position;
}
function next()
{
$this->position++;
}
function valid()
{
if ($this->result && FALSE !== ($row = mysql_fetch_assoc($this->result)))
{
$this->rows[]=$row;
}
return isset($this->rows[$this->position]);
}
}
//usage
$rows = new QueryIterator("SELECT * FROM users");
foreach($rows as $row)
print_r($row);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment