search
HomeBackend DevelopmentPHP ProblemHow to implement comment reply function in php
How to implement comment reply function in phpSep 12, 2021 am 09:57 AM
phpreplyComment

How to implement the comment reply function in php: 1. Design the data table; 2. Obtain the comment list through recursion; 3. Display the action of the comment page; 4. Display the overall structure design of the page; 5. Create a single Comment information p structure code; 6. Set the a label button style for replying to comments.

How to implement comment reply function in php

The operating environment of this article: windows7 system, PHP7.1 version, DELL G3 computer

How does php implement the comment reply function?

php unlimited classification to realize comment and reply function

You often see the comment function under the details page of major forums or news sections, of course not only It is so simple to post a comment directly. You can reply to other people's comments, and others can comment or reply to your reply again. This repeats, theoretically, it can be said to be endless. From a technical perspective, it is easy to think of using infinite classification technology. Store data, use recursion to obtain comment hierarchical structure data, and use ajax to implement comment page interaction. Here we use the thinkphp framework to make a simple demo to practice. In order to simplify the process, the third-level comments will start to stop replying. Of course, as long as you do a little work on this basis The infinite reply function can be realized by modifying it. The main reason is that modifying the view layer style is troublesome and takes some time.

1. Effect demand analysis:

1. You can publish first-level comments directly in the header, and the latest comments are displayed at the top, as shown in the following rendering

2. You can reply to posted comments, and the replies are displayed below the superior comments, forming a hierarchical relationship, as shown in the following rendering

# #3. Page operation details: When the reply button of a comment is clicked, the reply text input box is displayed, and the reply text input boxes of other comments disappear. When the reply button is clicked again, the text box disappears

4. Turn off the reply function at the last level of comments (the setting here is the third level)

5. Instantly display the total number of comments

2. Implementation ideas and details

1. Data table design

##2. Key functions of the controller layer: (1). Recursively obtain the comment list

/**
*递归获取评论列表
 */
 protected function getCommlist($parent_id = 0,&$result = array()){ 
 $arr = M('comment')->where("parent_id = '".$parent_id."'")->order("create_time desc")->select(); 
 if(empty($arr)){
 return array();
 }
 foreach ($arr as $cm) { 
 $thisArr=&$result[];
 $cm["children"] = $this->getCommlist($cm["id"],$thisArr); 
 $thisArr = $cm;     
 }
 return $result;
 }

(2). Display the action of the comment page

public function index(){ 
 $num = M('comment')->count(); //获取评论总数
 $this->assign('num',$num);
 $data=array();
 $data=$this->getCommlist();//获取评论列表
 $this->assign("commlist",$data);
 $this->display('index');
 }

(3). Comment page ajax access to add comment action

/**
*添加评论
 */
 public function addComment(){  
 $data=array();
 if((isset($_POST["comment"]))&&(!empty($_POST["comment"]))){
 $cm = json_decode($_POST["comment"],true);//通过第二个参数true,将json字符串转化为键值对数组
 $cm['create_time']=date('Y-m-d H:i:s',time());
 $newcm = M('comment');
 $id = $newcm->add($cm);

 $cm["id"] = $id;
 $data = $cm;

 $num = M('comment')->count();//统计评论总数
 $data['num']= $num;

 }else{
 $data["error"] = "0";
 }


 echo json_encode($data);
 }

3.View layer implementation(1). Display the overall structural design of the page

Actual effect:

##Page html code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 <title>php无限级分类实战————评论及回复功能</title>
 <link rel="stylesheet" type="text/css" href="/Public/css/comment.css" rel="external nofollow" >
 <script type="text/javascript" src="/Public/js/jquery-1.11.3.min.js" ></script>
 <script type="text/javascript" src="/Public/js/comment.js" ></script>
</head>
<body>

<p class="comment-filed">
 <!--发表评论区begin-->
 <p>
 <p class="comment-num">
 <span>{$num}条评论</span>
 </p>
 <p>
 <p>
 <textarea class="txt-commit" replyid="0"></textarea>
 </p>
 <p class="p-txt-submit">
  <a class="comment-submit" parent_id="0"  href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><span style=&#39;&#39;>发表评论</span></a>
 </p> 
 </p>
 </p>
 <!--发表评论区end-->

 <!--评论列表显示区begin-->
 <!-- {$commentlist} -->
 <p class="comment-filed-list" >
 <p><span>全部评论</span></p>
 <p class="comment-list" >
  <!--一级评论列表begin-->
  <ul class="comment-ul"> 
  <volist name="commlist" id="data">   
   <li comment_id="{$data.id}">   
   <p >
   <p>
    <img class="head-pic lazy"  src="/static/imghwm/default1.png"  data-src="{$data.head_pic}"    alt=""> 
   </p>
   <p class="cm">
    <p class="cm-header">
    <span>{$data.nickname}</span>
    <span>{$data.create_time}</span>
    </p>
    <p class="cm-content">
    <p>
     {$data.content}
    </p>
    </p>
    <p class="cm-footer">
    <a class="comment-reply" comment_id="{$data.id}" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >回复</a>   
    </p> 
   </p>        
   </p>

   <!--二级评论begin-->
   <ul class="children">
   <volist name="data.children" id="child" >    
   <li comment_id="{$child.id}">   
    <p >
    <p>
     <img class="head-pic lazy"  src="/static/imghwm/default1.png"  data-src="{$child.head_pic}"    alt=""> 
    </p>
    <p class="children-cm">
     <p class="cm-header">
     <span>{$child.nickname}</span>
     <span>{$child.create_time}</span>
     </p>
     <p class="cm-content">
     <p>
      {$child.content}
     </p>
     </p>
     <p class="cm-footer">    
     <a class="comment-reply" replyswitch="off" comment_id="{$child.id}" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >回复</a>
     </p> 
    </p>        
    </p>

    <!--三级评论begin-->
    <ul class="children">
    <volist name="child.children" id="grandson" > 
    <li comment_id="{$grandson.id}">   
     <p >
     <p>
      <img class="head-pic lazy"  src="/static/imghwm/default1.png"  data-src="{$grandson.head_pic}"    alt=""> 
     </p>
     <p class="children-cm">
      <p class="cm-header">
      <span>{$grandson.nickname}</span>
      <span>{$grandson.create_time}</span>
      </p>
      <p class="cm-content">
      <p>
       {$grandson.content}
      </p>
      </p>
      <p class="cm-footer">    
      <!-- <a class="comment-reply" comment_id="1" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >回复</a> -->
      </p> 
     </p>        
     </p>
    </li>
    </volist>
    </ul> 
    <!--三级评论end-->

   </li>
   </volist>
   </ul> 
   <!--二级评论end-->

  </li>
  </volist>         
  </ul>
  <!--一级评论列表end-->
 </p> 
 </p>
 <!--评论列表显示区end-->
</p> 
</body>
</html>

(2). The corresponding rendering of a single comment information p structure code

<p >
 <p>
 <img class="head-pic lazy"  src="/static/imghwm/default1.png"  data-src="{$data.head_pic}"    alt=""> 
 </p>
 <p class="cm">
 <p class="cm-header">
  <span>{$data.nickname}</span>
  <span>{$data.create_time}</span>
  </p>
 <p class="cm-content">
   <p>
   {$data.content}
   </p>
 </p>
 <p class="cm-footer">
  <a class="comment-reply" comment_id="{$data.id}" href="javascript:void(0);" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >回复</a>   
 </p> 
 </p>        
</p>

:

## The corresponding css code:

.head-pic{
 width:40px;
 height:40px; 
}

.cm{
 position:relative;
 top:0px;
 left:40px;
 top:-40px;
 width:600px;
}

.cm-header{
 padding-left:5px;
}

.cm-content{
 padding-left:5px;
}

.cm-footer{
 padding-bottom:15px;
 text-align:right;
 border-bottom: 1px dotted #CCC;
}

.comment-reply{
 text-decoration:none;
 color:gray;
 font-size: 14px;
}

4. JS code

(1). Submit comments: The a label button that submits comments references the style comment-submit, and performs ajax operations in its click event

$(&#39;body&#39;).delegate(&#39;.comment-submit&#39;,&#39;click&#39;,function(){ 
 var content = $.trim($(this).parent().prev().children("textarea").val());//根据布局结构获取当前评论内容
 $(this).parent().prev().children("textarea").val("");//获取完内容后清空输入框
 if(""==content){
  alert("评论内容不能为空!"); 
 }else{
  var cmdata = new Object();
  cmdata.parent_id = $(this).attr("parent_id");//上级评论id
  cmdata.content = content;
  cmdata.nickname = "游客";//测试用数据
  cmdata.head_pic = "/Public/images/default.jpg";//测试用数据  
  var replyswitch = $(this).attr("replyswitch");//获取回复开关锁属性
  $.ajax({
  type:"POST",
  url:"/index.php/home/index/addComment",
  data:{
   comment:JSON.stringify(cmdata)  
  },
  dataType:"json",  
  success:function(data){
   if(typeof(data.error)=="undefined"){
   $(".comment-reply").next().remove();//删除已存在的所有回复p 
   //更新评论总数   
   $(".comment-num").children("span").html(data.num+"条评论");
   //显示新增评论
   var newli = "";   
   if(cmdata.parent_id == "0"){
    //发表的是一级评论时,添加到一级ul列表中   
    newli = "<li comment_id=&#39;"+data.id+"&#39;><p ><p><img class=&#39;head-pic&#39; src=&#39;"+data.head_pic+"&#39; alt=&#39;&#39;></p><p class=&#39;cm&#39;><p class=&#39;cm-header&#39;><span>"+data.nickname+"</span><span>"+data.create_time+"</span></p><p class=&#39;cm-content&#39;><p>"+data.content+"</p></p><p class=&#39;cm-footer&#39;><a class=&#39;comment-reply&#39; comment_id=&#39;"+data.id+"&#39; href=&#39;javascript:void(0);&#39;>回复</a></p></p></p><ul class=&#39;children&#39;></ul></li>";    
    $(".comment-ul").prepend(newli);
   }else{
    //否则添加到对应的孩子ul列表中    
    if(&#39;off&#39;==replyswitch){//检验出回复关闭锁存在,即三级评论不再提供回复功能    
    newli = "<li comment_id=&#39;"+data.id+"&#39;><p ><p><img class=&#39;head-pic&#39; src=&#39;"+data.head_pic+"&#39; alt=&#39;&#39;></p><p class=&#39;children-cm&#39;><p class=&#39;cm-header&#39;><span>"+data.nickname+"</span><span>"+data.create_time+"</span></p><p class=&#39;cm-content&#39;><p>"+data.content+"</p></p><p class=&#39;cm-footer&#39;></p></p></p><ul class=&#39;children&#39;></ul></li>";
    }else{//二级评论的回复按钮要添加回复关闭锁属性   
    newli = "<li comment_id=&#39;"+data.id+"&#39;><p ><p><img class=&#39;head-pic&#39; src=&#39;"+data.head_pic+"&#39; alt=&#39;&#39;></p><p class=&#39;children-cm&#39;><p class=&#39;cm-header&#39;><span>"+data.nickname+"</span><span>"+data.create_time+"</span></p><p class=&#39;cm-content&#39;><p>"+data.content+"</p></p><p class=&#39;cm-footer&#39;><a class=&#39;comment-reply&#39; comment_id=&#39;"+data.id+"&#39; href=&#39;javascript:void(0);&#39; replyswitch=&#39;off&#39; >回复</a></p></p></p><ul class=&#39;children&#39;></ul></li>";
    }    
    $("li[comment_id=&#39;"+data.parent_id+"&#39;]").children("ul").prepend(newli);
   }

   }else{
   //有错误信息
   alert(data.error);
   }

  }
  });
 }


 });
(2). Reply to comments: The a label button that replies to comments references the style comment-reply, and displays or hides the comment input box in its click event

//点击"回复"按钮显示或隐藏回复输入框
 $("body").delegate(".comment-reply","click",function(){
 if($(this).next().length>0){//判断出回复p已经存在,去除掉
  $(this).next().remove();
  }else{//添加回复p
  $(".comment-reply").next().remove();//删除已存在的所有回复p 
  //添加当前回复p
  var parent_id = $(this).attr("comment_id");//要回复的评论id

  var phtml = "";
  if(&#39;off&#39;==$(this).attr("replyswitch")){//二级评论回复后三级评论不再提供回复功能,将关闭属性附加到"提交回复"按钮"
  phtml = "<p class=&#39;p-reply-txt&#39; style=&#39;width:98%;padding:3px;&#39; replyid=&#39;2&#39;><p><textarea class=&#39;txt-reply&#39; replyid=&#39;2&#39; style=&#39;width: 100%; height: 60px;&#39;></textarea></p><p style=&#39;margin-top:5px;text-align:right;&#39;><a class=&#39;comment-submit&#39; parent_id=&#39;"+parent_id+"&#39; style=&#39;font-size:14px;text-decoration:none;background-color:#63B8FF;&#39; href=&#39;javascript:void(0);&#39; replyswitch=&#39;off&#39; >提交回复</a></p></p>";
  }else{
  phtml = "<p class=&#39;p-reply-txt&#39; style=&#39;width:98%;padding:3px;&#39; replyid=&#39;2&#39;><p><textarea class=&#39;txt-reply&#39; replyid=&#39;2&#39; style=&#39;width: 100%; height: 60px;&#39;></textarea></p><p style=&#39;margin-top:5px;text-align:right;&#39;><a class=&#39;comment-submit&#39; parent_id=&#39;"+parent_id+"&#39; style=&#39;font-size:14px;text-decoration:none;background-color:#63B8FF;&#39; href=&#39;javascript:void(0);&#39;>提交回复</a></p></p>";
  }  
  $(this).after(phtml);
  }
 });

Recommended learning: "

PHP Video Tutorial

"

The above is the detailed content of How to implement comment reply function in php. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
php怎么把负数转为正整数php怎么把负数转为正整数Apr 19, 2022 pm 08:59 PM

php把负数转为正整数的方法:1、使用abs()函数将负数转为正数,使用intval()函数对正数取整,转为正整数,语法“intval(abs($number))”;2、利用“~”位运算符将负数取反加一,语法“~$number + 1”。

php怎么实现几秒后执行一个函数php怎么实现几秒后执行一个函数Apr 24, 2022 pm 01:12 PM

实现方法:1、使用“sleep(延迟秒数)”语句,可延迟执行函数若干秒;2、使用“time_nanosleep(延迟秒数,延迟纳秒数)”语句,可延迟执行函数若干秒和纳秒;3、使用“time_sleep_until(time()+7)”语句。

php字符串有没有下标php字符串有没有下标Apr 24, 2022 am 11:49 AM

php字符串有下标。在PHP中,下标不仅可以应用于数组和对象,还可应用于字符串,利用字符串的下标和中括号“[]”可以访问指定索引位置的字符,并对该字符进行读写,语法“字符串名[下标值]”;字符串的下标值(索引值)只能是整数类型,起始值为0。

php怎么除以100保留两位小数php怎么除以100保留两位小数Apr 22, 2022 pm 06:23 PM

php除以100保留两位小数的方法:1、利用“/”运算符进行除法运算,语法“数值 / 100”;2、使用“number_format(除法结果, 2)”或“sprintf("%.2f",除法结果)”语句进行四舍五入的处理值,并保留两位小数。

php怎么读取字符串后几个字符php怎么读取字符串后几个字符Apr 22, 2022 pm 08:31 PM

在php中,可以使用substr()函数来读取字符串后几个字符,只需要将该函数的第二个参数设置为负值,第三个参数省略即可;语法为“substr(字符串,-n)”,表示读取从字符串结尾处向前数第n个字符开始,直到字符串结尾的全部字符。

php怎么根据年月日判断是一年的第几天php怎么根据年月日判断是一年的第几天Apr 22, 2022 pm 05:02 PM

判断方法:1、使用“strtotime("年-月-日")”语句将给定的年月日转换为时间戳格式;2、用“date("z",时间戳)+1”语句计算指定时间戳是一年的第几天。date()返回的天数是从0开始计算的,因此真实天数需要在此基础上加1。

php怎么替换nbsp空格符php怎么替换nbsp空格符Apr 24, 2022 pm 02:55 PM

方法:1、用“str_replace("&nbsp;","其他字符",$str)”语句,可将nbsp符替换为其他字符;2、用“preg_replace("/(\s|\&nbsp\;||\xc2\xa0)/","其他字符",$str)”语句。

php怎么查找字符串是第几位php怎么查找字符串是第几位Apr 22, 2022 pm 06:48 PM

查找方法:1、用strpos(),语法“strpos("字符串值","查找子串")+1”;2、用stripos(),语法“strpos("字符串值","查找子串")+1”。因为字符串是从0开始计数的,因此两个函数获取的位置需要进行加1处理。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools