简体   繁体   English

在一个php类中还给多个mysql结果

[英]Give back more than one mysql result in an php class

I'm trying to build my own CMS in classes. 我正在尝试在课程中构建自己的CMS。
Now I have got a problem when I try to get data from my MySQL database 现在当我尝试从MySQL数据库获取数据时遇到问题
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 最后,我想获得一个对象,以便可以像这样读取它:$ 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 . 不要以开头$ where字符串.

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

and alwez print your $query 和alwez打印您的$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 并且可以通过$search_result[$i]->id检索任何$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 ..它已将数据库行作为对象返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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