Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- class MySQLi_Iterator implements Iterator {
- protected $classname = '\stdClass';
- protected $result = null;
- protected $current = null;
- protected $total = 0;
- protected $position = 0;
- protected $fetched = 0;
- public function __construct (MySQLi_Result $result, $classname = null) {
- $this->result = $result;
- $this->classname = $classname ?: '\stdClass';
- $this->total = $result->num_rows;
- $this->position = 0;
- $this->fetched = -1;
- }
- function rewind() {
- if($this->position > 0) {
- $this->position = 0;
- $this->fetched = -1;
- $this->result->data_seek(0);
- }
- }
- function current() {
- if($this->fetched != $this->position) {
- $this->current = $this->result->fetch_object($this->classname);
- $this->fetched = $this->position;
- }
- return $this->current;
- }
- function key() {
- return $this->position;
- }
- function next() {
- $this->position ++;
- }
- function valid() {
- return $this->position < $this->total;
- }
- }
- class User {
- public $id;
- public $firstname;
- public $lastname;
- public function display () {
- return trim($this->firstname . ' ' . $this->lastname);
- }
- }
- $mysqli = new MySQLi('localhost', 'username', 'password', 'databasename');
- $result = new MySQLi_Iterator($mysqli->query('SELECT * FROM `user`'), 'User');
- foreach($result as $user) {
- echo $user->display(), PHP_EOL;
- }
- // Nils Corver
- // Jacob Corver
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement