2

I'm not new to PHP, but I am new to all this PDO and MVC stuff. I'm basically trying to echo out data from the database to the page.

Model (_dashboard.php)

<?php

require_once('_connection.php');

class ConnectToDB {
    private $db;

    public function  __construct(){
        $this->db =new connection();
        $this->db = $this->db->dbConnection(); //uses the connection in connection class
    }

    public function teachersStudents($id){
        // this function checks whether the user name exists and if its a match
        if(!empty($id)){
            $st = $this->db->prepare("SELECT * FROM students WHERE id=?");
            $st->bindParam(1, $id);
            $st->execute();

            if ($st->rowCount() == 1) {
                $result = $st->fetchAll();
                foreach($result as $row){
                     echo "<tr>";
                     echo "<td>" . $row['id'] . "</td>";
                     echo "</tr>";
                 }
            } 
        } 
    }

}  

 // Close database connection
 $dbh = null; 

 ?>

View (dashboard.phtml)

<?php

    require_once('_dashboard.php');

    $object = new ConnectToDB();
    $object->teachersStudents($id); 

    echo $result; 
?>

Result

Notice: Undefined variable: result

I'm probably doing this completely wrong so a push in the right direction would be appreciated. Here's the controller but really has nothing to do with it.

Controller

<?php

    $view = new stdClass();
    $view->pageTitle = 'Dashboard';
    require_once('views/dashboard.phtml');
2
  • How do you pass $result from model to view? Commented Apr 5, 2015 at 2:14
  • There is a require_once i forgot to copy from the code, code updates Commented Apr 5, 2015 at 14:39

1 Answer 1

1

$result is undefined Change your function to return the result.

$result = $st->fetchAll();
return $result;

Then move your code to display HTML in the view instead:

require_once('_dashboard.php');

$object = new ConnectToDB();
$result = $object->teachersStudents($id); 

foreach($result as $row){
 echo "<tr>";
 echo "<td>" . $row['id'] . "</td>";
 echo "</tr>";
}
Sign up to request clarification or add additional context in comments.

4 Comments

Getting this on the page 'Warning: Invalid argument supplied for foreach()'
@CarlR did you modify your function like above? also do var_dump($result); to see the content of your array
var_dump($result); is giving NULL
Fixed it, i have a if condition i used in a login function i didn't remove when i copied the code, thanks :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.