tags:

views:

245

answers:

3

Hello Everyone,

Fortunately, I know how to fetch data from the database, That's not a problem. For my object oriented application I would have a table with users / persons. I also have a person class.

The case: I would like to show to the end user a list with all the persons. What is the correct way to show do this?

  1. using mysql_fetch_object() in this case php will create it's own type of object, not my own type of person
  2. Fetching all the rows from the db and then create an object of each?

Or is there an other better way to do it?

Can you also please show some (pseudo) code?

Thanks

+3  A: 
  • option 1: use ORM (Propeler, Doctrine)
  • option 2: create class People ("Persons"), which will load it's data using mysql_fetch_*, then create array of Person objects. Have it implement IteratorAggregate with getIterator returning ArrayIterator(personArray)
vartec
Thanks for your reaction. I have so fare created the iterator but don't really know how to use it.
sanders
if you have object People which implements IteratorAggregate, you can use it with: foreach (people as person) { doSomethingWith(person) }
vartec
Ok, I will try to work it out else I will elaborate on it in a different topic. Thanks so far.
sanders
+5  A: 

The mysql_fetch_object() function takes a second parameter, which is the class name to use:

$myPerson = mysql_fetch_object($result, 'person');
Greg
Don't forget to throw away references to objects after writing them out, else you'll exhaust your available memory if you have too many of them around.
David Schmitt
+2  A: 

If you use PDO, $pdoStatement->fetchObject($type) fetches a single row as instance of $type Class

To fetch all objects as instance of $type Class, use $pdoStatement->fetchAll(PDO::FETCH_CLASS, $type)

Imran
thanks for your reply. But we don't use the pdo class. We made our own
sanders