【问题标题】:PHP pdo fetch only returning 1 result [duplicate]PHP pdo fetch仅返回1个结果[重复]
【发布时间】:2015-02-24 14:39:12
【问题描述】:

pdo 函数:

        public function selectByCatagory($catagory,$column,$table,$id){
        $query =  $this->_pdo->prepare('SELECT ' .$column. ' FROM ' .$table. ' WHERE   catagory=:catagory');
        $query->bindParam(':catagory', $catagory);
        $query->execute();
        $result = $query->fetch();
        return $result[$id];
    }

功能使用:

            for($i = 0; $i < 11; $i++){
        $title = database::getInstance()->selectByCatagory($catagory, 'subject' , 'web_forum' ,$i);        
        echo $title

             }

获取偏移量 1 时出现问题。它说没有偏移量 1,但是当我在我的数据库程序中运行它时,还有 9 个其他结果。

【问题讨论】:

  • fetch 只返回第一行。要获取其他行,您必须再次调用它。
  • 谢谢!这行得通,这对我来说太愚蠢了。

标签: php html mysql pdo


【解决方案1】:

fetch 实际上只返回结果集中的一行。如果您想要所有这些,则必须使用 fetchAll 或自己迭代结果集:

public function selectByCatagory($catagory,$column,$table,$id){
    $query =  $this->_pdo->prepare('SELECT ' .$column. ' FROM ' .$table. ' WHERE   catagory=:catagory');
    $query->bindParam(':catagory', $catagory);
    $query->execute();

    $retVal = array();
    while ($result = $query->fetch()) {
        array_push($retVal, $result[$id]);
    }
    return $retVal;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-28
    • 2014-09-15
    • 2015-10-10
    • 2012-11-21
    • 2017-04-17
    相关资源
    最近更新 更多