记录一下我在学习《十天学会PHP》(第六版)的过程中的遇到的重难点,该课程是学习制作一个简单的留言板。
<?php
include('connect.php');
$sql = "SELECT * FROM msg ORDER BY id DESC";
$mysqli_result = $db->query($sql);
if ($mysqli_result === false) {
echo "SQL错误";
exit;
}
while ($row = $mysqli_result->fetch_array(MYSQL_ASSOC)) {
$rows[] = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>留言本</title>
<style>
.wrap{
width: 600px;
margin: 0px auto;
}
.add{
overflow: hidden;
}
.add .content{
width: 598px;
margin: 0;
padding: 0;
}
.add .user{
float: left;
}
.add .btn{
float: right;
}
.msg{
margin: 20px 0px;
background: #ccc;
padding: 5px;
}
.msg .info{
overflow: hidden;
}
.msg .user{
float: left;
color: blue;
}
.msg .time{
float: right;
color: #999;
}
.msg .content{
width: 100%;
}
</style>
</head>
<body>
<div class="wrap">
<!-- 发表留言 -->
<div class="add">
<form action="save.php" method="post">
<textarea name="content" class="content" cols="50" rows="5"></textarea>
<input name="user" class="user" type="text" />
<input class="btn" type="submit" value="发表留言" />
</form>
</div>
<?php
foreach ($rows as $row) {
?>
<!-- 查看留言 -->
<div class="msg">
<div class="info">
<span class="user"><?php echo $row['user'];?></span>
<span class="time"><?php echo date("Y-m-d H:i:s", $row['intime']);?></span>
</div>
<div class="content">
<?php echo $row['content'];?>
</div>
</div>
<?php
}
?>
</div>
</body>
</html>
<?php
//预先定义数据库链接参数
$host = '127.0.0.1';
$dbuser = 'root';
$password = '123456';
$dbname = 'php10';
$db = new mysqli($host, $dbuser, $password, $dbname);
if ($db->connect_errno <> 0) {
die('链接数据库失败');
}
//设定数据库数据传输?编码
$db->query("SET NAME UTF8");
?>
<?php
class input{
function post($content) {
if ($content == '') {
return false;
}
//禁止使用的用户名
$n = ['张三','李四','王五'];
foreach ($n as $name) {
if ($content == $name) {
return false;
}
}
return true;
}
}
?>
<?php
include('input.php');
include('connect.php');
$content = $_POST['content'];
$user = $_POST['user'];
$input = new input();
//调用函数,检查留言内容
$is = $input->post($content);
if ($is == false) {
die('留言内容的数据不正确');
}
//调用函数,检查留言人
$is = $input->post($user);
if ($is == false) {
die('留言人的数据不正确');
}
//数据入库
$time = time();
$sql = "INSERT INTO msg(content, user, intime) VALUES ('{$content}', '{$user}', '{$time}')";
$is = $db->query($sql);
header("location: gbook.php");
?>
原文:https://www.cnblogs.com/ofcean/p/11921730.html