1
我试图从我的数据库中获取所有结果。我有一个OOP结构,并在我的DB类中创建了几个函数,它可以从数据库获取所有结果。为foreach提供的参数无效()
public function getAll($table, $order) {
return $this->actionAll('SELECT *', $table, $order);
}
public function actionAll($action, $table, $order) {
$sql = "{$action} FROM {$table} ORDER BY {$order} DESC";
if(!$this->queryAll($sql)) {
return $this;
}
}
public function queryAll($sql) {
$this->_error = false;
if($this->_query = $this->_pdo->prepare($sql)) {
if($this->_query->execute()) {
$this->_results = $this->_query->fetchAll(PDO::FETCH_OBJ);
$this->_count = $this->_query->rowCount();
} else {
$this->_error = true;
}
}
}
在我的Page类中我调用了我的数据库类中的函数并计算结果。
public function get() {
$data = $this->_db->getAll('pages', 'created');
if($data->count()) {
$this->_data = $data->first();
return true;
}
}
接下来,我的列表中的PHP文件我打电话从我的Page类的get
功能,并通过成果创造一个foreach循环来。
<?php $page = new Page();
$pages = $page->get();
if(empty($pages)): ?>
<p>No pages at the moment</p>
<?php else: ?>
<?php foreach($pages as $item): ?>
<tr>
<td><?php echo e($item->data()->label); ?></td>
<td><?php echo e($item->data()->title); ?></td>
<td><a href="<?php echo BASE_URL; ?>/page.php?page=<?php echo e($item->data()->slug); ?>"><?php echo e($item->data()->slug); ?></a></td>
<td><a href="<?php echo BASE_URL; ?>/admin/edit.php?id=<?php echo e($item->data()->id); ?>">Edit</a></td>
<td><a href="<?php echo BASE_URL; ?>/admin/delete.php?id=<?php echo e($item->data()->id); ?>">Delete</a></td>
</tr>
<?php endforeach;
endif; ?>
问题是我得到错误为foreach()提供的无效参数。我不明白为什么我会得到这个错误。
我试图解决这个问题,但想不到一个解决方案。
更新了我的文章。忘了添加一行代码。 – Chris
你可以将'foreach'-block封装在'if(is_array($ pages)){/ * foreach * /}'中,从而确保你实际上是将一个数组传递给循环。如果它不是数组,则不能使用'foreach'循环。 – Qirel
**请**,试试这个:调用'$ page-> get();'后,使用'$ pages = $ page - > _ data;'或'$ pages = $ page - > _ results;'。如果你看一看,你只是将'null'的'true'赋给'$ pages',而不是'$ page'对象的结果。 – FirstOne