我正在尝试返回在我的页面上找到的html表上的结果的数量。我是第一次使用mvc框架,所以对于我来说,这个过程是非常新的。
我的查询成功地完成并显示了表格结果,我的问题可能是返回代码的定位?
我包括了我的代码,以供参考;
模型
public function categoryView()
{
$sth = $this->db->prepare("SELECT
b.id,
b.title,
b.category,
FROM book
WHERE status != 'Archive' AND category = :cat ORDER BY id DESC LIMIT 15");
$sth->bindValue(':cat', $_GET['category']);
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // won't run when included
return count($result); // won't run when included
$all_books = array();
foreach ($sth->fetchAll() as $book) {
$all_books[$book->id] = new stdClass();
$all_books[$book->id]->id = $book->id;
$all_books[$book->id]->title = $book->title;
$all_books[$book->id]->category = $book->cat_name;
}
return $all_books;
}视图
Found <?php echo count($result); ?> records
<table>
<?php
foreach ($this->books as $book) {
echo "<tr>";
echo '<td>'.$book->id.'</td>';
echo '<td>'.$book->title.'</td>';
echo '<td>'.$book->category.'</td>';
echo "</tr>";
}
?>
</table>控制器
function categoryView()
{
$categoryView_model = $this->loadModel('Books');
$this->view->books = $categoryView_model->categoryView();
$this->view->render('books/categoryView');
}我在“视图”页面上收到错误。
Warning: `Invalid argument supplied for foreach() ... on line 51`和
Found
Notice: Undefined variable: result in ... on line 47
0 records第47行包含Found <?php echo count($result); ?> records
第51行包含foreach ($this->books as $book) { ... }
如有任何建议或帮助,我们将不胜感激。
发布于 2014-12-19 15:58:42
移除这两行
$result = $sth->fetchAll(PDO::FETCH_ASSOC); // won't run when included
return count($result); // won't run when included在你看来改变
Found <?php echo count($result); ?> records至
Found <?php echo count($this->books); ?> records必须这样做的原因是在运行以下行时将从categoryView()返回的结果存储到视图的books属性中
$this->view->books = $categoryView_model->categoryView();请注意,计数总是最多为15。如果要显示已发现结果的总数#,则应发出一个单独的select count(*),而不包含limit子句。
发布于 2014-12-19 15:39:23
如果您指定了框架,这将对我们有很大帮助。老实说,我在Zend中只作为一个php框架工作过,但在那里,您必须将属性分配给您的视图:
$this->view->property = $all_books; //or any other property并在视图中检索它
<?php echo $this->property; ?>我发现很难想象MVC从视图中调用函数(action),在zend中,函数需要以特定的方式命名,因此需要使用返回。我告诉你一件事,你把变量发送到视图的方式是错误的,返回不能是发送它的正确方式。没有您的框架,这是我能帮助您的唯一方法,此外,我还会告诉您,实际上要回显两个变量的isset,您将看到我的理论是正确的--您没有正确地从控制器、操作或函数中发送变量。
https://stackoverflow.com/questions/27568986
复制相似问题