How to implement comment reply function in php
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.
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
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=''>发表评论</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>
<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>
.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$('body').delegate('.comment-submit','click',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='"+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);'>回复</a></p></p></p><ul class='children'></ul></li>";
$(".comment-ul").prepend(newli);
}else{
//否则添加到对应的孩子ul列表中
if('off'==replyswitch){//检验出回复关闭锁存在,即三级评论不再提供回复功能
newli = "<li comment_id='"+data.id+"'><p ><p><img class='head-pic' src='"+data.head_pic+"' alt=''></p><p class='children-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'></p></p></p><ul class='children'></ul></li>";
}else{//二级评论的回复按钮要添加回复关闭锁属性
newli = "<li comment_id='"+data.id+"'><p ><p><img class='head-pic' src='"+data.head_pic+"' alt=''></p><p class='children-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);' replyswitch='off' >回复</a></p></p></p><ul class='children'></ul></li>";
}
$("li[comment_id='"+data.parent_id+"']").children("ul").prepend(newli);
}
}else{
//有错误信息
alert(data.error);
}
}
});
}
});
//点击"回复"按钮显示或隐藏回复输入框 $("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('off'==$(this).attr("replyswitch")){//二级评论回复后三级评论不再提供回复功能,将关闭属性附加到"提交回复"按钮" phtml = "<p class='p-reply-txt' style='width:98%;padding:3px;' replyid='2'><p><textarea class='txt-reply' replyid='2' style='width: 100%; height: 60px;'></textarea></p><p style='margin-top:5px;text-align:right;'><a class='comment-submit' parent_id='"+parent_id+"' style='font-size:14px;text-decoration:none;background-color:#63B8FF;' href='javascript:void(0);' replyswitch='off' >提交回复</a></p></p>"; }else{ phtml = "<p class='p-reply-txt' style='width:98%;padding:3px;' replyid='2'><p><textarea class='txt-reply' replyid='2' style='width: 100%; height: 60px;'></textarea></p><p style='margin-top:5px;text-align:right;'><a class='comment-submit' parent_id='"+parent_id+"' style='font-size:14px;text-decoration:none;background-color:#63B8FF;' href='javascript:void(0);'>提交回复</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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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

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

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

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,

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

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 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.
