Jump to content

Passing data from controller to view MVC


ScoobyDont

Recommended Posts

Hi 

I will try and explain this as best I can, as I am not sure if the "include" is causing the problem.

What I am trying to achieve is count the total number of vehicles in the "vehicles" db table and pass it to views (I have recently moved over to MVC so still learning so please be kind and keep it simple for me please)

I have a folder in views called "vehicletracker" , within this folder I have 2 files "index.php" and "widget.php".........The "widget.php" file  is an "include" within "index php".

The problem I am having is passing data from the controller to the view, I keep getting an "Undefined index: total" error and wonder if someone can help and show me where I am going wrong.

This is my Model

 

 <?php

 class Widget {
    private $db;
    
    public function __construct(){
      $this->db = new Database;
    }
      
      public function countVehicles(){
      $this->db->query("SELECT * FROM vehicles");
      return $this->db->rowCount();
    }  
      
      
  }

This is my controller

 

<?php
  class Widgets extends Controller{
    public function __construct(){
     $this->widgetModel = $this->model('Widget');
        
    
   public function widget (){
       $data['total'] = $this->widgetModel->countVehicles();
       $this->view('vehicletracker/widget', $data);
   }
        
        
}

And my view

 

<h2 class="text-white"><?php echo $data['total']; ?></h2>

 

Thanks in advance for any help you can give

Link to comment
Share on other sites

Quote

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement. However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

If you want a count, then  SELECT a count.

Edited by benanamen
Link to comment
Share on other sites

hi, 

I have changed the code a little bit and put everything in my index page to try and to get it to work, I am not getting the Undefined error anymore I am just getting a 0 value with everything I do.

The new revised code 

Model

<?php

public function countVehicles (){
  $this->db->query("SELECT COUNT(id) FROM vehicles WHERE id = :id");
  $counter = $this->db->rowCount();
  return $counter;
  
}

 And Controller

 

<?php

public function index(){
  $counter = $this->vehicleModel->countVehicles();
  
  $data = [
  	'counter' => $counter
  ];
  
  $this->view('vehicletracker/index', $data);
}

And View

<?php 

<h2><?php echo $data['counter'];?></h2>

 

Like mentioned I am just getting a return of 0, 

If someone can point me in the right direction it would be much appreciated

And please KISS (Keep It Simple as I am Stupid)

Link to comment
Share on other sites

Let's look at your method:

public function countVehicles (){
  $this->db->query("SELECT COUNT(id) FROM vehicles WHERE id = :id");
  // Where is the :id parameter?  You do not pass it into the method nor do you pass it to the query
  $counter = $this->db->rowCount();  // This, should it work, will always return 1.  Not what you want! 
  return $counter;  
}

 

You do not want to do a rowcount on that query, because it will always be 1.  Select count(id) is going to always return one row.  Even if there is 1 row counted or a million, or zero.  The reason the query was suggested is that it will always have a value.  With that said, you would need to fetch the row to access the value, not count the number of rows in the result set.  

Personally, in order to have a simple column name to use, I will alias the result of a count() query like the one suggested.  Here is how I would do it:

"SELECT COUNT(*) as count_of FROM vehicles"

Then if you have fetched this result into a variable in some way, you can expect to access the value via something like $row['count_of'].

With that said, your query by id, assuming that id is the primary key of the vehicles table, will always count at most one row, because the primary key must be unique.  There are compound keys that could complicate this, but I don't see anything you are doing that suggests you have a table with a compound key.  Are you just trying to get this to work, so that you can do what you *really* want to do?

I'm going to assume you actually want the count of all vehicles as you did initially.  If things were working as they should, your original code should have worked.  Something is not working in your database model/class.

Unfortunately, I can render no further aid, because I would need to know more about what "MVC" you are using.   MVC is a design pattern, not an implementation, and has been implemented in various ways by nearly every popular PHP framework, with a few exceptions.

What framework are you using, or is this something you have built yourself from scratch?  What is the source of the database class?  

 

Link to comment
Share on other sites

Wow thank you for your detailed repsonse, 

The MVC is one I followed on a tutorial online, here is a copy of my Database Lib

<?php
	/* 
   *  PDO DATABASE CLASS
   *  Connects Database Using PDO
	 *  Creates Prepeared Statements
	 * 	Binds params to values
	 *  Returns rows and results
   */
class Database {
	private $host = DB_HOST;
	private $user = DB_USER;
	private $pass = DB_PASS;
	private $dbname = DB_NAME;
	
	private $dbh;
	private $error;
	private $stmt;
	
	public function __construct() {
		// Set DSN
		$dsn = 'mysql:host=' . $this->host . ';dbname=' . $this->dbname;
		$options = array (
			PDO::ATTR_PERSISTENT => true,
			PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION 
		);

		// Create a new PDO instanace
		try {
			$this->dbh = new PDO ($dsn, $this->user, $this->pass, $options);
		}		// Catch any errors
		catch ( PDOException $e ) {
			$this->error = $e->getMessage();
		}
	}
	
	// Prepare statement with query
	public function query($query) {
		$this->stmt = $this->dbh->prepare($query);
	}
	
	// Bind values
	public function bind($param, $value, $type = null) {
		if (is_null ($type)) {
			switch (true) {
				case is_int ($value) :
					$type = PDO::PARAM_INT;
					break;
				case is_bool ($value) :
					$type = PDO::PARAM_BOOL;
					break;
				case is_null ($value) :
					$type = PDO::PARAM_NULL;
					break;
				default :
					$type = PDO::PARAM_STR;
			}
		}
		$this->stmt->bindValue($param, $value, $type);
	}
	
	// Execute the prepared statement
	public function execute(){
		return $this->stmt->execute();
	}
	
	// Get result set as array of objects
	public function resultset(){
		$this->execute();
		return $this->stmt->fetchAll(PDO::FETCH_OBJ);
	}
	
	// Get single record as object
	public function single(){
		$this->execute();
		return $this->stmt->fetch(PDO::FETCH_OBJ);
	}
	
	// Get record row count
	public function rowCount(){
		return $this->stmt->rowCount();
	}
    
	// Returns the last inserted ID
	public function lastInsertId(){
		return $this->dbh->lastInsertId();
	}
}

If you could see any errors that is causing the problem it would be appreciated, I will also look at what you have previously sent and get  back to you if I get stuck

Link to comment
Share on other sites

1 hour ago, benanamen said:

Link please. Based on the DB class, the tutorial is less than optimal.

Oh great, to be honest it was to help me start to understand MVC of which I first thought it seemed quite simple until I tried to do a simple bloody count

Now I am starting to wonder what ever was wrong with 

<?
$carcount = $db->query("SELECT id FROM vehicledetails WHERE id=id");
$carscounted = $carcount->rowCount();
?>

It was a course on Udemy,(£9.99)  and to be fair I thought it had given me an insight into MVC but by your response maybe not.

OT but which framework would you recommend for a beginner/advancing php'er

 

Link to comment
Share on other sites

7 hours ago, benanamen said:

Just to clarify, my response had nothing to do with MVC. It was with the Database Class itself.

Thank you, I fully understand that and thank you for your input, but everything I seem to do with this framework seems to give me problems. So I have ditched it, so I no longer need any more answers on the topic.

Yesterday I carried out some testing with Laravel, Cake and CodeIgniter and out of the 3 I personally like CI so going to run with that.

Thanks again for all your help 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.