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

标签 php mysql model-view-controller pdo

我不是 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

我可能做的完全错了,所以向正确的方向插入将不胜感激。这是 Controller ,但实际上与它无关。

Controller

<?php

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

最佳答案

$result 未定义 更改您的函数以返回结果。

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

然后移动您的代码以在 View 中显示 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>";
}

关于php - PDO MVC 将数据从数据库回显到页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29452484/

相关文章:

php - PHP 代码中的 SQL 语法错误,即使命令在命令行中运行

php - 链接导致 IE 中的行间距问题

php - 如何在cakephp中以逗号值分隔搜索

MySQL 从与表名的连接返回字段和数据?

c# - View 未编译时不重定向到错误页面

ruby-on-rails - 如何在 Feed 上提交多态评论? [错误]

java - Spring MVC。 HTTP 状态 404

php - 如何在 Symfony2 中用 Doctrine2 生成的实体指定 setter 名称?

mysql - 计算出现在时间间隔 2 中的时间间隔 1 中的条目数 - SQL

php - 如何使用 PHP7 从静态方法调用特征的非静态方法?