PDO MVC 将数据从数据库回显到页面

PDO MVC Echoing data from database to page

我不是 PHP 的新手,但我是所有这些 PDO 和 MVC 的新手。我基本上是在尝试将数据从数据库回显到页面。

型号 (_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; 

 ?>

查看 (dashboard.phtml)

<?php

    require_once('_dashboard.php');

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

    echo $result; 
?>

结果

Notice: Undefined variable: result

我可能完全错了,所以如果能朝正确的方向推进,我们将不胜感激。这是控制器,但实际上与它无关。

控制器

<?php

    $view = new stdClass();
    $view->pageTitle = 'Dashboard';
    require_once('views/dashboard.phtml');

$result 未定义 将您的函数更改为 return 结果。

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

然后移动您的代码以在视图中显示 HTML:

require_once('_dashboard.php');

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

foreach($result as $row){
 echo "<tr>";
 echo "<td>" . $row['id'] . "</td>";
 echo "</tr>";
}