先看一下实战结果,下面再分享实战过程
image.png
准备:phpStorm+wampserver+chrome浏览器+准备好的前端代码、js、css、图片(下面没框住的部分都是准备好的)
image.png
1、数据库连接公共部分 connect.php
<?php
<?php
/**
* Created by PhpStorm.
* User: zjy
* Date: 2018/7/13
* Time: 8:42
*/
// 面向对象方式连接
$mysqli = new mysqli('localhost','root','','imoocComment');
if ($mysqli->errno){
// 连接错误数>1 输出错误
die("Connect Error: " + $mysqli->error);
}else{
$mysqli->set_charset("utf8");
}
2、写Comment类
<?php
class Comment{
private $data=array();
// 构造函数 初始化数据
function __construct($data){
$this->data=$data;
}
/**
* 检测用户输入的数据
* @param array $arr
* @return boolean
*/
public static function validate(&$arr){
if(!($data['email']=filter_input(INPUT_POST,'email',FILTER_VALIDATE_EMAIL))){
$errors['email']='请输入合法邮箱';
}
if(!($data['url']=filter_input(INPUT_POST,'url',FILTER_VALIDATE_URL))){
$url='';
}
// 检测判断使用回调函数
if(!($data['content']=filter_input(INPUT_POST,'content',FILTER_CALLBACK,array('options'=>'Comment::validate_str')))){
$errors['content']='请输入合法内容';
}
if(!($data['username']=filter_input(INPUT_POST,'username',FILTER_CALLBACK,array('options'=>'Comment::validate_str')))){
$errors['username']='请输入合法用户名';
}
// 数组范围 options设置成1到5
$options=array(
'options'=>array(
'min_range'=>1,
'max_range'=>5
)
);
if(!($data['face']=filter_input(INPUT_POST,'face',FILTER_VALIDATE_INT,$options))){
$errors['face']='请选择合法头像';
}
if(!empty($errors)){
$arr=$errors;
return false;
}
$arr=$data;
// 邮箱字母转小写
$arr['email']=strtolower(trim($arr['email']));
return true;
}
/**
* 过滤用户输入的特殊字符
* @param string $str
* @return boolean|string
*/
public static function validate_str($str){
// gb2312中,strlen计算字符长度时,一个中文字符算2个长度。 utf8 一个中文字符算3个长度
if(mb_strlen($str,'UTF8')<1){
return false;
}
$str=nl2br(htmlspecialchars($str,ENT_QUOTES));
return $str;
}
/**
* 显示评论内容
* @return string
*/
public function output(){
$link_start = '';
$link_end = '';
if($this->data['url']){
$link_start="<a href='".$this->data['url']."' target='_blank'>";
$link_end="</a>";
}
$dateStr=date("Y年m月d日 H:i:s",$this->data['pubTime']);
$res=<<<EOF
<div class='comment'>
<div class='face'>
{$link_start}
<img width='50' height='50' src="img/{$this->data['face']}.jpg" alt="" />
{$link_end}
</div>
<div class='username'>
{$link_start}
{$this->data['username']}
{$link_end}
</div>
<div class='date' title='发布于{$dateStr}'>
{$dateStr}
</div>
<p>{$this->data['content']}</p>
</div>
EOF;
return $res;
}
}
3、doAction.php 先检测用户提交的数据,检测通过后才入库提交。
<?php
/**
* Created by PhpStorm.
* User: zjy
* Date: 2018/7/13
* Time: 8:40
*/
header("content-type:text/html;charset=utf-8");
require_once 'connect.php';
require_once 'comment.class.php';
// 为什么不用_POST 映射到数组?? 数组怎么提交到数组的$arr
$arr = array();
$res = Comment::validate($arr);
if ($res){
$sql = "insert into comments(username,email,url,face,content,pubTime) values(?,?,?,?,?,?);";
$mysqli_stmt = $mysqli->prepare($sql);
$arr['pubTime'] = time();
$mysqli_stmt->bind_param("sssssi",$arr['username'],$arr['email'],$arr['url'],$arr['face'],$arr['content'],$arr['pubTime']);
$mysqli_stmt->execute();
$comment = new Comment($arr);
echo json_encode(array('status'=>1,'html'=>$comment->output()));
}else{
echo '{"status":0,"errors":'.json_encode($arr).'}';
}
4、index.php,在每次刷新首页时需要显示数据信息,先查询评论,再显示出来
<?php
require_once 'connect.php';
require_once 'comment.class.php';
// 先准备好数据进行显示
$sql="SELECT username,email,url,face,content,pubTime FROM comments";
$mysqli_result=$mysqli->query($sql);
if($mysqli_result&& $mysqli_result->num_rows>0){
while($row=$mysqli_result->fetch_assoc()){
$comments[]=new Comment($row);
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<title>Document</title>
<link rel="stylesheet" type="text/css" href="style/style.css" />
</head>
<body>
<h1>慕课网评论系统</h1>
<div id='main'>
<?php
if(!(empty($comments))){ // 当查询到有评论数据时,则进行显示
foreach($comments as $val){
echo $val->output();
}
}
?>
<div id='addCommentContainer'>
<form id="addCommentForm" method="post" action="">
<div>
<label for="username">昵称</label>
<input type="text" name="username" id="username" required='required' placeholder='请输入您的昵称'/>
<label for="face">头像</label>
<div id='face'>
<input type="radio" name="face" checked='checked' value="1" /><img src="img/1.jpg" alt="" width='50' height='50' />
<input type="radio" name="face" value="2" /><img src="img/2.jpg" alt="" width='50' height='50' />
<input type="radio" name="face" value="3" /><img src="img/3.jpg" alt="" width='50' height='50' />
<input type="radio" name="face" value="4" /><img src="img/4.jpg" alt="" width='50' height='50' />
<input type="radio" name="face" value="5" /><img src="img/5.jpg" alt="" width='50' height='50' />
</div>
<label for="email">邮箱</label>
<input type="email" name="email" id="email" required='required' placeholder='请输入合法邮箱'/>
<label for="url">个人博客</label>
<input type="url" name="url" id="url" />
<label for="content">评论内容</label>
<textarea name="content" id="content" cols="20" rows="5" required='required' placeholder='请输入您的评论...'></textarea>
<input type="submit" id="submit" value="发布评论" />
</div>
</form>
</div>
</div>
<script type="text/javascript" src="script/jquery.min.js"></script>
<script type="text/javascript" src="script/comment.js"></script>
</body>
</html>