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;
 }
Copy after login

(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');
 }
Copy after login

(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);
 }
Copy after login

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>
Copy after login

(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>
Copy after login

:

## 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;
}
Copy after login

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);
   }

  }
  });
 }


 });
Copy after login
(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);
  }
 });
Copy after login

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

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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

7 PHP Functions I Regret I Didn't Know Before 7 PHP Functions I Regret I Didn't Know Before Nov 13, 2024 am 09:42 AM

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

See all articles