gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 02:57:12 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com