I am trying to return the number of results found on my page above an html table. I am using an mvc framework for the first time so it's very new to me how the process works.
My query works and displays the tabular results successfully, my issue is [probably] with the positioning of my return code?
I have included my code for reference;
Model
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;
}
View
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>
Controller
function categoryView()
{
$categoryView_model = $this->loadModel('Books');
$this->view->books = $categoryView_model->categoryView();
$this->view->render('books/categoryView');
}
I receive the error errors on my view page
Warning: `Invalid argument supplied for foreach() ... on line 51`
and
Found
Notice: Undefined variable: result in ... on line 47
0 records
Line 47 contains Found <?php echo count($result); ?> records
Line 51 contains foreach ($this->books as $book) { ... }
Any advice or help is appreciated.
Remove these two lines
In your view change
to
The reason you have to do this is because you're storing the results returned from
categoryView()
into thebooks
property of the view when you run the following lineNote that the count will always be a maximum of 15. If you want to display the total # of found results you should issue a separate
select count(*)
without alimit
clause.