PHP开发 发表评论功能教程之PHP页面

先来看PHP读取和生成JSON数据的server.php代码。

0.jpg

代码如下

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$conn=mysqli_connect("localhost","root","root","comments");
mysqli_set_charset($conn,"utf8");
$sql="SELECT * from comments";
$que=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($que)){
      $comments[] = array("id"=>$row[id],"user"=>$row[user],"comment"=>$row[comment],"addtime"=>$row[addtime]);
}
echo json_encode($comments);
?>

注意:你的PHP版本应该是5.2以上才能使用json_encode函数。


comments.php 代码

comment.php接收前台ajax提交过来的昵称和评论内容参数,判断参数的合法性,然后将数据插入到数据库中,如果成功,则输出1,返回给前台jQuery处理。

<?php
header("Content-type:text/html;charset=utf-8");    //设置编码
$user = htmlspecialchars(trim($_POST['user']));
$txt = htmlspecialchars(trim($_POST['txt']));
$time = date("Y-m-d H:i:s");
if(empty($user)){
   echo "昵称不能为空!";
   exit;
}
if(empty($txt)){
   echo "评论内容不能为空!";
   exit;
}
$conn=mysqli_connect("localhost","root","root","comments");
mysqli_set_charset($conn,"utf8");
$sql="insert into comments(user,comment,addtime)values('$user','$txt','$time')";
$que=mysqli_query($conn,$sql);
if($que)  echo "1";
?>


我们将我们的HTML页面跟PHP代码组合起来,就能实现我们的评论功能了


本例使用简单容易的代码诠释了轻量、高效的jQuery结合PHP的ajax运作机制,当然这只是一个基础的例子,jQuery还能做很多事情,留给大家去尽情发挥吧。


继续学习
||
<?php header("Content-type:text/html;charset=utf-8"); //设置编码 $conn=mysqli_connect("localhost","root","root","comments"); mysqli_set_charset($conn,"utf8"); $sql="SELECT* from comments"; $que=mysqli_query($conn,$sql); while($row=mysqli_fetch_array($que)){ $comments[] = array("id"=>$row[id],"user"=>$row[user],"comment"=>$row[comment],"addtime"=>$row[addtime]); } echo json_encode($comments); ?>
提交重置代码
  • 推荐课程
  • 评论
  • 问答
  • 笔记
  • 课件下载
依然范特西

依然范特西

不行啊

3年前    添加回复 2

回复
逝幕、的年華

逝幕、的年華

王企鹅

3年前    添加回复 1

回复
无言

无言

评论区评论倒是可以实现

3年前    添加回复 0

mingge55555

怎么实现的啊

mingge55555 · 2018-11-14 15:27
回复
无言

无言

不能实现效果啊

3年前    添加回复 0

回复
为什么我还是学渣

为什么我还是学渣

额 数据库是存进去数据了 但是 传不到网页上

3年前    添加回复 0

回复
虎斑猫

虎斑猫

网页打不开

4年前    添加回复 0

回复
虎斑猫

虎斑猫

打不开啊

4年前    添加回复 0

回复
课件暂不提供下载,工作人员正在整理中,后期请多关注该课程~