-3

我不明白我的错误,因为我肯定有一个 oject。看下面我的print_r

注意:尝试在第 21 行的 C:\xampp\htdocs\travel_mvc\cockpit\index.php 中获取非对象的属性

第 21 行并有:

echo $row->tz_name.'<br>';

我的 print_r:

Array
(
    [0] => stdClass Object
        (
            [tz_name] => Africa/Abidjan
        )

    [1] => stdClass Object
        (
            [tz_name] => Africa/Accra
        )

    [2] => stdClass Object
        (
            [tz_name] => Africa/Addis_Ababa
        )

    [3] => stdClass Object
        (
            [tz_name] => Africa/Algiers
        )

    [4] => stdClass Object
        (
            [tz_name] => Africa/Asmara
        )

)

在我的课堂上,我有:

class model{
    private $fields = '*';
    private $table = '';
    private $where = '';
    private $and = '';
    private $limit = '';
    private $order = '';
    private $type_order = 'DESC';
    private $d = array();

    public function find($data = array()){
        if(isset($data['fields'])){
            $this->fields = $data['fields'];
        }
        $this->table = $data['table'];
        if(isset($data['where'])){
            $this->where = ' WHERE '.$data['where'];
        }
        if(isset($data['and'])){
            $this->and = ' WHERE '.$data['and'];
        }
        if(isset($data['limit'])){
            $this->limit = ' LIMIT '.$data['limit'];
        }
        if(isset($data['order'])){
            $this->order = ' ORDER BY '.$data['order'].$type_order;
        }
        $query = Db::getInstance()->prepare('SELECT '.$this->fields.' 
                                             FROM '.$this->table.$this->where.
                                             $this->and.$this->order.$this->limit.'');
        $query->execute();
        while($data = $query->fetchAll(PDO::FETCH_OBJ)){
            $d[] = $data;
        }
        return($d);
    }
}

当我调用我的函数时:

$model = new model();
$sql = $model->find(array(
    'fields'=>'tz_name',
    'table'=>'times_zones',
    'limit'=>5
));
foreach($sql as $row):
    echo $row->tz_name.'<br>';
endforeach;
echo '<pre>';
print_r($row);
echo '</pre>';
4

1 回答 1

1

PDOStatement::fetchAll()已经返回了一个数组,所以你只是无缘无故地双重嵌套了结果集。

在您的model::find()方法中,更改这些行...

while($data = $query->fetchAll(PDO::FETCH_OBJ)){
    $d[] = $data;
}
return($d);

return $query->fetchAll(PDO::FETCH_OBJ);

您也可以删除该model $d属性(不是您一直在使用它)。

于 2013-07-22T06:37:27.853 回答