RR_1990
RR_1990

Reputation: 13

Give back more than one mysql result in an php class

I'm trying to build my own CMS in classes.
Now I have got a problem when I try to get data from my MySQL database
Instead of one item i'd like to get an collection of all my items

At the end I'd like to get an Object so I can read it out like : $item->id

Here's my code :

static function getContentItems($id, $active, $sort_by, $sort_type, $limit) {
    if (isset($id) && !empty($id)) {
        $where .= "WHERE id = ".$id;
    }
    if (isset($active) && !empty($active)) {
        $where .= " AND active = ".$active;
    }
    if (isset($sort_by) && !empty($sort_by)) {
        $where .= " ORDER BY ".$sort_by;

        if (isset($sort_type) && !empty($sort_type)) {
            $where .= " ".$sort_type;
        }
    }
    if (isset($limit) && !empty($limit)) {
        $where .= " LIMIT 0,".$limit;
    }

    if (isset($where) && !empty($where)) {
        $query = "SELECT * FROM content ".$where;   
    } else {
        $query = "SELECT * FROM content";
    }
    $result = mysql_query($query)or die(mysql_error());

    $item = new ContentItem();
    while ($data = mysql_fetch_array($result)) { 
        $item->id = $data['id'];
    }   
    return $item;
}

}

Upvotes: 0

Views: 228

Answers (3)

xkeshav
xkeshav

Reputation: 54074

dont start your $where string with .

if (isset($id) && !empty($id)) {
        $where = "WHERE id = ".$id;
    }

and alwez print your $query

Better Solution

if (!empty($id) {
        $where = " WHERE id = ".$id;
   if (!empty($active)) {
          $where .= " AND active = ".$active;
     if (!empty($sort_by)) {
          $where .= " ORDER BY ".$sort_by;
        if (!empty($sort_type)) {
            $where .= " ".$sort_type;
        }
    }
  }
}
if (empty($limit)) {
        $where .= " LIMIT 0,".$limit;
}

and later

$item = new ContentItem();       
$data = array(); $i=0;
while ($data = mysql_fetch_object($result)) {                
         $search_result[$i] = $data;
         $i++;
    }   
 return $search_result;

and any id can be retrieve by $search_result[$i]->id

Upvotes: 1

bonez
bonez

Reputation: 695

Look into using mysql_fetch_object http://php.net/manual/en/function.mysql-fetch-object.php instead of mysql_fetch_array.. it returns rows the db as an object already

Upvotes: 0

gtatweb
gtatweb

Reputation: 1

Why don't you use Arrays?

Like this:

$collection = array();
while ($data = mysql_fetch_array($result)) {
    $item = new ContentItem();
    $item->id = $data['id'];
    $collection[] = $item;     //Appends the item to the array
}
return $collection;

You can access your array in this way:

$collection = YourClassName::getContentItems(...);
foreach($collection as $item) {
    // do something with each $item
    print_r($item);
}

Upvotes: 0

Related Questions