Home Backend Development PHP Problem How to implement comment reply function in php

How to implement comment reply function in php

Sep 12, 2021 am 09:57 AM
php reply Comment

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" style="" 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" 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" 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" 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" 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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are public, private, and protected in php What are public, private, and protected in php Aug 24, 2025 am 03:29 AM

Public members can be accessed at will; 2. Private members can only be accessed within the class; 3. Protected members can be accessed in classes and subclasses; 4. Rational use can improve code security and maintainability.

How to execute an UPDATE query in php How to execute an UPDATE query in php Aug 24, 2025 am 05:04 AM

Using MySQLi object-oriented method: establish a connection, preprocess UPDATE statements, bind parameters, execute and check the results, and finally close the resource. 2. Using MySQLi procedure method: connect to the database through functions, prepare statements, bind parameters, perform updates, and close the connection after processing errors. 3. Use PDO: Connect to the database through PDO, set exception mode, pre-process SQL, bind parameters, perform updates, use try-catch to handle exceptions, and finally release resources. Always use preprocessing statements to prevent SQL injection, verify user input, and close connections in time.

How to use cURL in php How to use cURL in php Aug 24, 2025 am 08:32 AM

cURLinPHPenablessendingHTTPrequests,fetchingAPIdata,anduploadingfiles.Initializewithcurl_init(),setoptionslikeCURLOPT_URLandCURLOPT_RETURNTRANSFER,useCURLOPT_POSTforPOSTrequests,sendJSONwithproperheaders,handleerrorsviacurl_errno()andHTTPcodeswithcur

How to read a CSV file in PHP? How to read a CSV file in PHP? Aug 29, 2025 am 08:06 AM

ToreadaCSVfileinPHP,usefopen()toopenthefile,fgetcsv()inalooptoreadeachrowasanarray,andfclose()tocloseit;handleheaderswithaseparatefgetcsv()callandspecifydelimitersasneeded,ensuringproperfilepathsandUTF-8encodingforspecialcharacters.

How to use AJAX with php How to use AJAX with php Aug 29, 2025 am 08:58 AM

AJAXwithPHPenablesdynamicwebappsbysendingasynchronousrequestswithoutpagereloads.1.CreateHTMLwithJavaScriptusingfetch()tosenddata.2.BuildaPHPscripttoprocessPOSTdataandreturnresponses.3.UseJSONforcomplexdatahandling.4.Alwayssanitizeinputsanddebugviabro

Edit bookmarks in chrome Edit bookmarks in chrome Aug 27, 2025 am 12:03 AM

Chrome bookmark editing is simple and practical. Users can enter the bookmark manager through the shortcut keys Ctrl Shift O (Windows) or Cmd Shift O (Mac), or enter through the browser menu; 1. When editing a single bookmark, right-click to select "Edit", modify the title or URL and click "Finish" to save; 2. When organizing bookmarks in batches, you can hold Ctrl (or Cmd) to multiple-choice bookmarks in the bookmark manager, right-click to select "Move to" or "Copy to" the target folder; 3. When exporting and importing bookmarks, click the "Solve" button to select "Export Bookmark" to save as HTML file, and then restore it through the "Import Bookmark" function if necessary.

What is the difference between isset and empty in php What is the difference between isset and empty in php Aug 27, 2025 am 08:38 AM

isset()checksifavariableexistsandisnotnull,returningtrueevenforzero,false,oremptystringvalues;2.empty()checksifavariableisnull,false,0,"0","",orundefined,returningtrueforthese"falsy"values;3.isset()returnsfalsefornon-exi

How to configure SMTP for sending mail in php How to configure SMTP for sending mail in php Aug 27, 2025 am 08:08 AM

Answer: Using the PHPMailer library to configure the SMTP server can enable sending mails through SMTP in PHP applications. PHPMailer needs to be installed, set up SMTP host, port, encryption method and authentication credentials of Gmail, write code to set sender, recipient, topic and content, enable 2FA and use application password to ensure that the server allows SMTP connection, and finally call the send method to send email.

See all articles