为了更好地展示数据,通常会创建对应的视图模板来达到更好的效果。
1.创建展示所有数据的视图模板
student_list.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>学生列表</title>
</head>
<body>
<h2 align="center">学生信息表</h2>
<table border="1" cellpadding="5" cellspacing="0" align="center" width="60%">
<tr bgcolor="#87ceeb">
<th>ID</th>
<th>姓名</th>
<th>邮箱</th>
<th>课程</th>
<th>成绩</th>
</tr>
<?php foreach ($data as $stu): ?>
<tr align="center">
<td><?php echo $stu['id']; ?></td>
<td><?php echo $stu['name']; ?></td>
<td><?php echo $stu['email']; ?></td>
<td><?php echo $stu['course']; ?></td>
<td><?php echo $stu['grade']; ?></td>
</tr>
<?php endforeach;?>
</table>
<p align="center">共计:<?php echo count($data); ?>条记录</p>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>学生信息</title>
</head>
<body>
<h2 align="center">学生信息</h2>
<table border="1" cellpadding="5" cellspacing="0" align="center" width="60%">
<tr align="center" bgcolor="#87ceeb">
<th>字段</th>
<th>值</th>
</tr>
<tr align="center">
<td>id</td>
<td><?php echo $data['id']; ?></td>
</tr>
<tr align="center">
<td>姓名</td>
<td><?php echo $data['name']; ?></td>
</tr>
<tr align="center">
<td>邮箱</td>
<td><?php echo $data['email']; ?></td>
</tr>
<tr align="center">
<td>课程</td>
<td><?php echo $data['course']; ?></td>
</tr>
<tr align="center">
<td>成绩</td>
<td
<?php
if ($data['grade'] < 60) {
echo 'style="color:red"';
}
?>
>
<?php echo $data['grade']; ?>
</td>
</tr>
</table>
<p align="center"
<?php
if ($data['grade'] < 60) {
echo 'style="color:red"';
}
?>
>
<?php
if ($data['grade'] < 60) {
echo '不及格,需要补考~~';
} else {
echo '恭喜及格~~';
}
?>
</p>
</body>
</html>
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
项目目录结构如下:
3.引入视图模板
修改StudentController.php中的方法,引入新创建的视图模板。
/**
* 获取所有数据
* @return mixed
*/
public function listAll()
{
// 实例化模型,获取数据
$stu = new StudentModel();
$data = $stu->getAll();
// 格式化
//echo '<pre>';
//print_r($data);
require_once 'view/student_list.php'; // 渲染模板
//return $data;
}
/**
* 获取单条数据
* @return mixed
*/
public function info($id=1)
{
$id = isset($_GET['id']) ? $_GET['id'] : $id;
// 实例化模型,获取数据
$stu = new StudentModel();
$data = $stu->get($id);
//echo '<pre>';
//print_r($data);
require_once 'view/student_info.php'; // 渲染模板
//return $data;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
4.查看视图模板效果
查询所有数据:http://localhost/php.cn/mvc/
查询单条记录:http://localhost/php.cn/mvc/?a=info&id=9