php - PDO FETCH_CLASS multiple rows into array of objects -


i'm trying fetch multiple rows of bookings database , want each 1 instance of specific class - attempted store them within multidimensional array.

so far works in terms of creating array of objects, need index array booking id can access each one. example:

$bookings[id] => booking object ( [name:protected] => name, [time:protected] => time ) 

is possible , best way go want achieve? hugely appreciated, here's code:

class create_bookings {       private $db;   protected $error;     function __construct($db, $current, $end) {      $this->db = $db;       $query = "select id, name, time                            bookings";      $stmt = $this->db->prepare($query);       $stmt->execute();       $result = $stmt->fetchall(pdo::fetch_class, 'booking');         print_r($result);  }  } 

...and 'booking' class set of properties:

class booking {        private $db;      protected $name;     protected $time;   } 

instead of building class create booking objects, advisable either create standalone function, or function within parent class achieve this. issue run in using fetchall() fetch_class parameter, objects not automatically have access database object, causing need iterate on objects afterwards anyways, build __construct() method capture $db , generated array.

assuming go route of standalone function:

function create_bookings($db, $current, $end) {     $query = "select id, name, time                            bookings";      $stmt = $db->prepare($query);       $stmt->execute();       $result = array()      $bookings = $stmt->fetchall();     if($bookings) {         foreach($bookings $booking) {             $result[$booking['id']] = new booking($db, $booking);         }     }     return $result; }   class booking {      private $db;     public $id;     public $name;     public $time;      public function __construct($db, $array) {         if(/*validate array here*/) {             $this->db = $db;             $this->id = $array['id'];             $this->name = $array['name'];             $this->time = $array['time'];         }     } } 

Comments

Popular posts from this blog

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -

javascript - oscilloscope of speaker input stops rendering after a few seconds -