进展顺利。但是我真的很想了解如何在视图类中获取和显示数据,而不必在数据库类中执行此操作。
PDO将数据作为关联数组返回,我通过实例化一个新的Controller Object使它可用于视图。
但是我似乎无法遍历返回的结果并在View中生成表。在获取的数据上执行print_r()确实可行,因此我知道该数组保存数据。我认为只是不知道如何在视图中正确访问对象。
任何人都可以帮忙,希望有道理,
谢谢麦克风。
下面的代码不显示任何内容。而且没有控制台或其他页面错误。那么如何显示数据?
模型----------------------------------------------- --------------
<?php
class Database {
private static $host = "*****";
private static $dbname = "*****";
private static $dbusername = "*****";
private static $dbpassword = "*****";
public static function connect() {
$pdo = new PDO("mysql:host=".self::$host.";dbname=".self::$dbname."", self::$dbusername,
self::$dbpassword);
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $pdo;
}
public function FetchAll() {
$getStudents = "SELECT * FROM StudentTable";
$stmt = $this->connect()->prepare($getStudents);
$stmt->execute();
$fetchResult = $stmt->fetchAll();
return $fetchResult;
}
}
?>
控制器----------------------------------------------- --------------
class Controller extends Database { public function MyReadMethod() { self::FetchAll(); } } public function MyCreateMethod($n,$p){ self::Create($n,$p); }
查看----------------------------------------------- --------------
<h1>Read & Show Data</h1> <?php $obj = new controller(); $results = $obj->MyReadMethod(); ?> <h1>Display All Students</h1> <table class="table"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr> </thead> <tbody> <?php while ($results = $row): ?> <tr> <td><?php echo htmlspecialchars($row['FirstName']) ?></td> <td><?php echo htmlspecialchars($row['LastName']); ?></td> <td><?php echo htmlspecialchars($row['Age']); ?></td> </tr> <?php endwhile; ?> </tbody> </table>
下面是一种有效的方法;我可以直接在数据访问层(数据库类)中输出数据。但这不是我要使用的方法,因为我想使用foreach或while循环直接在View上迭代数据。
public function ReadAll() { $getAll = "SELECT * FROM StudentTable"; $stmt = $this->connect()->query($getAll); while($row = $stmt->fetch()) { echo $row['FirstName']. '<br>' . $row['LastName']; } }
thought所要执行的。
此作品:while($row = $stmt->fetch())
但是不会:
<?php while ($results = $row): ?>
前者使用fetch()
遍历数组,但后者将null
($ row未定义)分配给$result
。您可能在想什么
foreach($result as $row):