gpt4 book ai didi

php - 在 php 类中返回多个 mysql 结果

转载 作者:行者123 更新时间:2023-11-29 14:53:30 26 4
gpt4 key购买 nike

我正在尝试在类里面构建自己的 CMS。
现在,当我尝试从 MySQL 数据库获取数据时遇到问题
我想要获得所有项目的集合,而不是一个项目

最后我想得到一个对象,这样我就可以像这样读出它:$item->id

这是我的代码:

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

}

最佳答案

不要以 开头 $where 字符串。

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

然后 alwez 打印您的 $query

更好的解决方案

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

及以后

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

并且任何 id 都可以通过 $search_result[$i]->id

检索

关于php - 在 php 类中返回多个 mysql 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5203773/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com