PHP OOP: how to get database rows as objects?

I can do this when I select a single-line tone, but tilt it to do this for multiple lines of data.

For one row, I simply create an instance of a new object that performs several operations behind the scenes that basically produce a row from the database as our object.

Example:

$object = new Classname($param); foreach($object->row as $key=>$value) { echo $key.":".$value."\n"; } //output id:1 firstname:steve lastname:took etc... 

Any smart people here can point me in the right direction, please?

NOTE: you just want to be able to create an object for each row, and not for a single object with nested arrays

EDIT: sorry $ object-> row is a member of the class that stores the selected row from the database

+4
source share
4 answers

Why don't you consider using ORM (Object Relational Mapper) like Doctrine or Propel? I prefer the Doctrine: http://www.doctrine-project.org/ Enjoy! :)

0
source

If I got you, the answer is quite simple mysql_fetch_object

Example:

 while ($row = mysql_fetch_object($result)) { echo $row->user_id; echo $row->fullname; } 
+5
source

Here is an example

 class users extends db { public $users_id = 0; public $users_group = 0; public $users_firstname = 0; public $users_lastname = 0; public function open($id) { if (is_numeric($id)) { $sql = "SELECT * FROM users WHERE users_id = '$id'"; $res = parent::DB_SELECT($sql); if (mysql_num_rows($res) <> 1) { return 0; } } else { $sql = "SELECT * FROM users " . $id; $res = parent::DB_SELECT($sql); if (mysql_num_rows($res) <= 0) { return 0; } } $data = array(); while ($row = mysql_fetch_array($res)) { $this->users_id = $row['users_id']; $this->users_group = $row['users_group']; $this->users_firstname = $row['users_firstname']; $this->users_lastname = $row['users_lastname']; $data[] = (array) $this; } return $data; } public function setUsersId($users_id) { $this->users_id = addslashes($users_id); } public function getUsersId() { return stripslashes($this->users_id); } public function setUsersGroup($users_group) { $this->users_group = addslashes($users_group); } public function getUsersGroup() { return stripslashes($this->users_group); } public function setUsersFirstname($users_firstname) { $this->users_firstname = addslashes($users_firstname); } public function getUsersFirstname() { return stripslashes($this->users_firstname); } public function setUsersLastname($users_lastname) { $this->users_lastname = addslashes($users_lastname); } public function getUsersLastname() { return stripslashes($this->users_lastname); } } 
0
source

You can use MySQLi.

  // Connect
 $ db = new mysqli ('host', 'user', 'password', 'db');

 // Query
 $ users = $ db-> query ('SELECT * from users');

 // Loop
 while ($ user = $ users-> fetch_object ()) {
     echo $ users-> field;
 }

 // close
 $ users-> close ();
 $ db-> close ();

Additional information here: http://php.net/manual/en/book.mysqli.php

0
source

All Articles