0

Just trying to get my head around MVC and having a little trouble with counting the amount of widgets in the database.

I am not sure if this is what is screwing it up but on my index page I have this

        <?php require APPROOT . '/views/inc/header.php'; ?>

          Some Other stuff here

        <?php require APPROOT . '/views/inc/widget.php'; ?>

Model

        <?php
     class Widget {
        private $db;

        public function __construct(){
          $this->db = new Database;
        }

        public function countWidgets(){
          $this->db->query("SELECT id FROM widgets WHERE id=id");
          $count = $this->db->rowCount();
           }

Controller

<?php
         class Widgets extends Controller{
            public function __construct(){
              // Load Models
              $this->widgetModel = $this->model('Widget');
            }

        public function widget(){
              $count = $this->widgetModel->countWidgets();
              $data = [
                'count' => $count
              ];
              $this->view('inc/widget', $data);
            }  
        }

And View

<div class="media-body text-right">
  <h2 class="text-white"><?php echo $count->id; ?></h2>
  <span>Total Widgets</span>
</div>

All I seem to get is this error Notice: Trying to get property 'id' of non-object in C:\xampp\htdocs\app\views\inc\widget.php on line 29

If anyone can give me a pointer where I am going wrong it would be much much appreciated, and thanks in advance for any help you can give.

Thanks Molly

  • `rowCount()`, I assume, it returning an integer not an object. Also, you aren't `return`ing anything from the Model to the Controller so `$count` is never populated in the Controller. For these reasons, there isn't a property named `id` in `$count`. Moreover, `id=id` is an absolutely useless WHERE clause condition since it will not filter out any rows. If you need a `$count->id` value, you will need to generate an object from the result set (not count how many rows are in the result set), then your View will stop barking back at you. – mickmackusa Nov 20 '20 at 03:51
  • I am voting to close this question as off-topic typo since this mistake/misunderstanding is not likely to help future researchers. This page could also be easily closed as a duplicate of MANY pages such as https://stackoverflow.com/q/5891911/2943403 – mickmackusa Nov 20 '20 at 03:51

0 Answers0