I am working with a new mvc framework ( view here ) and I have ran into a slight problem.
I have a table named ' favourite
' which looks like below;
---------------------------
id user_id book_id
1 2 1777
2 3 1887
3 2 1023
4 7 8776
5 2 8811
---------------------------
I am trying to display the number of favourites for a specific on their profile page ( Hello. You have x favourites ). I feel I am misunderstanding something regarding the mvc structure or have a syntax issue somewhere?
On my showprofile I don't have any errors, it's simply blank where the count should be. When I run the query in phpmyadmin I get a result of 3 which is correct.
I have read that rowCount() can be unreliable so I have also tried fetchColumn() amongst other variations. Do I need to use a second query?
New to php/sql/mvc so any advice is appreciated.
My code is as follows;
login_model.php (model)
class LoginModel
{
public function favouriteTotal()
{
$query = $this->db->prepare("SELECT COUNT(book_id) FROM favourite WHERE user_id = 2");
$query->execute();
$count = $query->rowCount()
}
}
showprofile.php (view)
<div>
Hello. Your have this number of favourites:
<?php echo $this->count ?>
</div>
login.php (controller)
class Login extends Controller
{
function showProfile()
{
$login_model = $this->loadModel('Login');
$this->view->count = $login_model->favouriteTotal();
$this->view->render('login/showprofile');
}
}
Your issue is that you're executing a COUNT query, when you should be using a SELECT query if you want to use the rowCount function.
This query would let your rowCount function work:
SELECT `book_id` FROM favourite WHERE user_id = 2
Alternatively, you could continue to use the COUNT statement, but you would then need to get the first result from your query instead of a row count.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.