数据库仅返回首行问题求助:SELECT全表查询异常排查
问题分析与解决方案
你的推测完全正确——问题根源就在DB类的query方法中调用的fetch_object()!
为什么只返回第一行?
mysqli::fetch_object()方法的作用是从结果集中获取当前行并返回为对象,每次调用只会取一行,调用后指针会移动到下一行。但你的代码里只调用了一次,所以$_result只存储了结果集的第一行数据,而num_rows能正确统计总行数是因为它直接读取结果集的总行数属性,和是否读取所有行无关。
修复步骤
1. 修改query方法,获取所有结果行
把原来只取单行的逻辑改成获取所有行的数组:
方法一:使用fetch_all()(推荐,更简洁)
public function query($sql) { $this->_error = false; if ($this->_query = $this->_conn->query($sql)) { // 用MYSQLI_OBJECT参数获取所有行的对象数组 $this->_result = $this->_query->fetch_all(MYSQLI_OBJECT); $this->_count = $this->_query->num_rows; } else { $this->_error = true; } return $this; }
方法二:循环读取每一行(兼容旧版本PHP)
如果你的PHP版本不支持fetch_all()(PHP 5.3+才支持),可以用循环遍历结果集:
public function query($sql) { $this->_error = false; if ($this->_query = $this->_conn->query($sql)) { $this->_result = []; // 循环读取每一行,存入数组 while ($row = $this->_query->fetch_object()) { $this->_result[] = $row; } $this->_count = $this->_query->num_rows; } else { $this->_error = true; } return $this; }
2. 确保results()方法返回完整结果数组
你的Index.php中调用了results()方法,这个方法应该直接返回$_result属性,确认你的DB类中有这个方法:
public function results() { return $this->_result; }
额外安全提醒
你的action方法存在SQL注入风险——直接将$value拼接到SQL语句中,如果$value来自用户输入(比如表单、URL参数),攻击者可以构造恶意SQL破坏你的数据库。建议改用mysqli预处理语句:
修改action方法中带where条件的分支:
if(count($where) === 3) { $operators = array('=', '>', '<', '>=', '<='); $field = $where[0]; $operator = $where[1]; $value = $where[2]; if(in_array($operator, $operators)) { // 使用占位符?代替直接拼接值 $sql = "{$action} FROM {$table} WHERE {$field} {$operator} ?"; $stmt = $this->_conn->prepare($sql); // 根据$value的类型绑定参数:i=整数,s=字符串,d=浮点数,b=二进制 $stmt->bind_param('i', $value); // 如果id是整数用i,字符串用s $stmt->execute(); $result = $stmt->get_result(); $this->_result = $result->fetch_all(MYSQLI_OBJECT); $this->_count = $result->num_rows; $this->_error = false; return $this; } }
这样修改后,$db->get('pages')就能返回所有行的数据了,而$db->get('pages', ["id", "=", 2])也能继续正常工作。
内容的提问来源于stack exchange,提问作者Lankhaar
相关产品推荐
相关产品推荐

