RR_1990
RR_1990

Reputation: 13

Object Collection

I'm making a class which needs to provide me with all the data from the MySQL-table "content".

I want to have my data returned as an object. So far I managed to get one object returned, but i'd like to get an Object Collection with all my rows from the database returned.

<?
class ContentItem {
public $id;
public $title;
public $subtitle;
public $conent;
public $intro_length;
public $active;
public $start_date;
public $end_date;
public $views;

static function getContentItems() {     
    $query = "SELECT * FROM content";

    $result = mysql_query($query)or die(mysql_error());
    $item = new ContentItem(); 
    while ($data = mysql_fetch_object($result)) {
          $item = $data;                            
    } 
    return $item;           
  }
}

Upvotes: 1

Views: 2002

Answers (3)

Ondrej Slint&#225;k
Ondrej Slint&#225;k

Reputation: 31910

For collections you need to create an object which implements Iterator interface. You can fill it with arrays, objects or whatever you want. Iterator makes sure you can use this collection in foreach loops after.

Furthermore, there's a mistake in your code. You are overwriting $item over and over again. You should create an array (or object with implemented Iterator, as I mentioned) which will be filled each cycle of while (as tandu wrote already).

Upvotes: 5

lunixbochs
lunixbochs

Reputation: 22415

The simple solution would be an array. I also assume you want a ContentItem made from each set of $data

$items = array();
while ($data = mysql_fetch_object($result)) {
      $items[] = new ContentItem($data);
} 
return $items;

If you later want to work with the items, you can use foreach

foreach ($items as $item) {
    // do something with $item
}

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191749

Your loop keeps overwriting data with item, and new ContentItem() is overwritten immediately. If by "object collection" you mean "array," it's quite simple:

$items = array();
while ($data = mysql_fetch_object($result)) {
   $items[] = $data;
}
return $items;

If you want to return your own custom object collection, then define the collection class and add $data to its collection each time (probably stored in an array as well).

Upvotes: 1

Related Questions