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