Advertisement
NilsCorver

PHP Iterator - MySQLi

Nov 9th, 2011
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.40 KB | None | 0 0
  1. <?php
  2.  
  3. class MySQLi_Iterator implements Iterator {
  4.     protected $classname = '\stdClass';
  5.     protected $result = null;
  6.     protected $current = null;
  7.     protected $total = 0;
  8.     protected $position = 0;
  9.     protected $fetched = 0;
  10.    
  11.     public function __construct (MySQLi_Result $result, $classname = null) {
  12.         $this->result = $result;
  13.         $this->classname = $classname ?: '\stdClass';
  14.         $this->total = $result->num_rows;
  15.         $this->position = 0;
  16.         $this->fetched = -1;
  17.     }
  18.    
  19.     function rewind() {
  20.         if($this->position > 0) {
  21.             $this->position = 0;
  22.             $this->fetched = -1;
  23.             $this->result->data_seek(0);
  24.         }
  25.     }
  26.    
  27.     function current() {
  28.         if($this->fetched != $this->position) {
  29.             $this->current = $this->result->fetch_object($this->classname);
  30.             $this->fetched = $this->position;
  31.         }
  32.         return $this->current;
  33.     }
  34.    
  35.     function key() {
  36.         return $this->position;
  37.     }
  38.    
  39.     function next() {
  40.         $this->position ++;
  41.     }
  42.    
  43.     function valid() {
  44.         return $this->position < $this->total;
  45.     }
  46. }
  47.  
  48. class User {
  49.     public $id;
  50.     public $firstname;
  51.     public $lastname;
  52.    
  53.     public function display () {
  54.         return trim($this->firstname . ' ' . $this->lastname);
  55.     }
  56. }
  57.  
  58. $mysqli = new MySQLi('localhost', 'username', 'password', 'databasename');
  59. $result = new MySQLi_Iterator($mysqli->query('SELECT * FROM `user`'), 'User');
  60.  
  61. foreach($result as $user) {
  62.     echo $user->display(), PHP_EOL;
  63. }
  64. // Nils Corver
  65. // Jacob Corver
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement