PHP PDO类数据提取

时间:2015-06-03 10:07:28

标签: php pdo

您好我正在使用我已经在this网站下载的PDO课程,这是我选择所有数据$results = $db->select("accounts");的代码。这是类中的函数

public function run($sql, $bind="") {
    $this->sql = trim($sql);z
    $this->bind = $this->cleanup($bind);
    $this->error = "";

    try {
        $pdostmt = $this->prepare($this->sql);
        if($pdostmt->execute($this->bind) !== false) {
            if(preg_match("/^(" . implode("|", array("select", "describe", "pragma")) . ") /i", $this->sql))
                return $pdostmt->fetchAll(PDO::FETCH_ASSOC);
            elseif(preg_match("/^(" . implode("|", array("delete", "insert", "update")) . ") /i", $this->sql))
                return $pdostmt->rowCount();
        }   
    } catch (PDOException $e) {
        $this->error = $e->getMessage();    
        $this->debug();
        return false;
    }
}

public function select($table, $where="", $bind="", $fields="*") {
    $sql = "SELECT " . $fields . " FROM " . $table;
    if(!empty($where))
        $sql .= " WHERE " . $where;
    $sql .= ";";
    return $this->run($sql, $bind);
}

我的问题是我想在while循环中回显数据,但我遇到了问题。现在我使用print_r($results)检查数据库中的数据。我试过了

while($row=$results->fetch(PDO::FETCH_ASSOC)) 
{ echo $row['Somefield']; } 

我收到此错误。 Fatal error: Call to a member function fetch() on a non-object。如何将该代码置于while或foreach循环中?

1 个答案:

答案 0 :(得分:1)

正如我在上面的评论中所述,包装的PDO类会进行PDOStatement::fetchAll()调用,并从db::select()返回结果。

因此,您需要像对待任何其他数组一样迭代$results

foreach ($results as $result) {
    echo $result['Somefield'];
}