Reputation: 13
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
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
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
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