简体   繁体   中英

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;
}

}

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

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);
}

查看使用mysql_fetch_object http://php.net/manual/zh/function.mysql-fetch-object.php而不是mysql_fetch_array ..它已将数据库行作为对象返回

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM