这篇内容将叙述数据库读取,先把首页预写的那2条留言删除,不过要保留格式
<ul class="mes-board">
<li>
<h4></h4>
<small></small>
<p></p>
</li>
</ul>
然后写入数据库读取代码,完整的代码如下:
<pre name="code" class="html"><!DOCTYPE html>
<?php
require "conn.php";
//设置输出编码
$conn->query("set names utf8");
//读取数据库
$sql = "select * from message order by id desc";
$result = $conn->query($sql);
?>
<html lang="zh-cn">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
<meta charset="UTF-8">
<title>留言板</title>
<link rel="stylesheet" href="style/style.css">
<!--[if lt IE 9]>
<script src="http://cdn.bootcss.com/html5shiv/r29/html5.js"></script>
<![endif]-->
</head>
<body>
<div class="wrap">
<!-- 留言显示区 -->
<ul class="mes-board">
<?php
if ($result->num_rows > 0) {
//逐行输出数据
while ($row = $result->fetch_assoc()) {
echo "<li><h4>" . $row["user_name"] . "</h4><small>" . $row["send_time"] . "</small><p>" . $row["user_mes"] . "</p></li>";
}
}else {
echo "暂无留言";
}
?>
</ul>
<section class="mes-send">
<form method="post" action="send.php">
<div class="form-group">
<label for="user_name">姓名:</label>
<input type="text" id="user_name" name="user_name" placeholder="用户名称">
</div>
<div class="form-group">
<label for="user_mes">留言:</label>
<textarea id="user_mes" name="user_mes" rows="5"></textarea>
</div>
<input type="submit" id="btn" value="提 交">
</form>
</section>
</div>
<?php $conn->close(); ?>
</body>
</html>
$sql = "select * from message order by id desc";
这里的星号是通配符,意味着读取所有字段的值,可以用具体的字段来代替
$sql = "select user_name,user_mes,send_time from message order by id desc";
追求效率推荐后者,也建议大家如果不是读取表的所有字段,用后面的方式具体列出字段来写。
order by id desc是让读取的结果按照id的降序来排序,升序是asc,默认为升序。
<?php
if ($result->num_rows > 0) {
//逐行输出数据
while ($row = $result->fetch_assoc()) {
echo "<li><h4>" . $row["user_name"] . "</h4><small>" . $row["send_time"] . "</small><p>" . $row["user_mes"] . "</p></li>";
}
}else {
echo "暂无留言";
}
?>
$result->num_rows 返回结果集中的行数。
while ($row = $result->fetch_assoc()) 返回数据集的关联数组,并移动内部的数据指针。这句话的意思就是数据表中的所有数据为一个集合,从第一条数据数组(包含相应字段)开始读取,读完一条指针自动指向第二条,以此类推。这里的fetch_assoc()可以用fetch_array()来代替,两者区别在于,前者只能用字段来读取数据,例如:$row["user_name"],不能用索引来读取数据,例如$row[1] (索引1正式字段user_name的位置,0为字段id);后者既可以用字段也可以用索引,也可以用字段。
留言板的基本功能基本实现啦,后面还会继续发展留言板,从简单的留言板发展为更具功能的留言板或其他,因为我还没想好往哪边发展。