search
HomeBackend DevelopmentPHP TutorialPHP: Create an Infinitus comment module

The comment module of my graduation project was originally completed using the Duoshuo plug-in, but now I hope to be able to manage the comment content myself, so I started writing the comment module myself. The specific preparation is to adopt a similar structure to the next comment, that is, the first-level comments are displayed directly below the article, while the second- and third-level comments are displayed below the first-level comments, as shown in the following figure:

PHP: Create an Infinitus comment module

Comment structure

I think this can be said to be an application of Infinitus classification. To be precise, it is the application of descendant trees. After classifying descendant trees, loop Output the content and form a comment (Friends who don’t understand Infinitus classification can read my article Principles and Implementation of Infinitus Classification).

Of course, there are other key points to truly complete the function of Infinitus replying to comments. Let’s talk about how I completed Infinitus comments.

Database Design

First of all, it is the design of the data table. If it is a forum system, the comment data can be divided into two tables. One table stores the comment information, including the user id of the post or the user id of the reply, and the post id## of the reply. #, Reply time, etc.; another table stores the content of the comment, including the topic of the post and the content of the reply.

What I have completed is the comment module of the article. It is not divided into two tables. I directly put the content and information of the comment together, as follows:

Column nameColumn typeColumnDescriptioncomm_idINTUNSIGNED PRIMARY Primary Keyuser_idINTUNSIGNED NOT useridparent_idINTUNSIGNED NOT NULL DEFAULT 0Parent of commentartcile_idINTUNSIGNED NOT NULL DEFAULT 0 Commented article idcomm_contTEXTCommented contentcomm_INTUNSIGNED NOT NULL DEFAULT 0

SQL statement:

CREATE TABLE comment (
    comm_id INT UNSIGNED PRIMARY KEY AUTO_INCREMENT,
    user_id INT UNSIGNED NOT NULL DEFAULT 0 ,
    parent_id INT UNSIGNED NOT NULL DEFAULT 0 ,
    article_id INT UNSIGNED NOT NULL DEFAULT 0 ,
    comm_cont TEXT,
    comm_time INT UNSIGNED NOT NULL DEFAULT 0 
) ENGINE=MYISAM CHARSET=UTF8 ;

This structure is the basis for completing Infinitus reply. It can also be clearly seen that the retrieved data can be well classified by Infinitus.

Structure analysis of comments

It is very easy to complete a comment module. Put the comments into the database, then retrieve them and place them in html. The comment module can also be completed. However, this structure is very messy and disorderly. If you want to complete a comment module like a comment, you have to use a special method.

Then, we need to take a closer look at the structure of comments.

PHP: Create an Infinitus comment module

Comment structure

Combined with the above data table structure, we can infer that the data taken out from the data table and classified by Infinitus, Its structure should be like this:

array (
    array(一级评论,
        child=>array(
            二级评论,
            三级评论
            )
        ),
    array (
        一级评论 ,
        child=>array(
            )
    ……

Why do you say that? You can clearly see that the second- and third-level comments are wrapped in the first-level comments, and the second- and third-level comments are parallel relationships; therefore, the second- and third-level comments are descendant nodes of the first-level comments, and Second-level and third-level comments are parallel nodes, and there is no parent-child relationship.

Therefore, it can be concluded that the classified data has and has only one descendant node. Whether a multi-level comment is a reply to a first-level comment or not, as long as it is within the scope of a first-level comment, then its parent node It must be a first-level review.

So, how is the @XXXX in the second-level and third-level replies implemented? Actually, I was troubled here for a long time. I expected to use a self-join to the table to complete, but this does not work, destroying the structure described above. Finally, I got the answer from the requested json data, please see the commented json data:

PHP: Create an Infinitus comment module

##JSON data

It’s a bit blurry after uploading. Students can use the plug-in on Firefox or Google Chrome to observe the JSON data.

Focus on the

compiled_content field, and you can infer that it stores @XXXX directly into the database. In this way, the problem is solved. At the same time, observing the json data can also verify that the structure I mentioned above is correct.

Specific implementation

After analyzing the structure, let’s talk about how to complete Infinitus reply. The first step is to form a first-level comment. This is simple, just store the comment directly

PHP: Create an Infinitus comment module

First-level comment

And second-level comment Using js, when you click on a comment, get the user name of the first-level comment and save it. When posting a reply, be sure to combine it with the content of the comment and send it to the background:

PHP: Create an Infinitus comment module

Second level comments

// replyUser 即 被回复的用户名 @xxxx
var content = $('#reply').val.split(replyUser)[1];
var userlink = '<a>' + replyUser + '</a>';
var comm_cont = encodeURIComponent(userlink+content);
Then the performance in the database is as follows:

PHP: Create an Infinitus comment module

Data table content

After It is a key point to use the descendant tree for classification. The classification

function is as follows:

/**
 * @param $data array  数据
 * @param $parent  string 父级元素的名称 如 parent_id
 * @param $son     string 子级元素的名称 如 comm_id
 * @param $pid     int    父级元素的id 实际上传递元素的主键
 * @return array 
 */
function getSubTree($data , $parent , $son , $pid = 0) {
    $tmp = array();
    foreach ($data as $key => $value) {
        if($value[$parent] == $pid) {
            $value['child'] =  getSubTree($data , $parent , $son , $value[$son]);
            $tmp[] = $value;            
        }
    }
    return $tmp;
}
After such classification, the data structure changes, roughly as follows:

PHP: Create an Infinitus comment module

Classified data

With this structure, you can easily complete comments, as follows

<?php  foreach($tree as $key=>$val) ?>
<p>
    </p><h2><?php  echo $val[&#39;user_name&#39;];?></h2>
    <p><?php  echo $val[&#39;comm_cont&#39;] ?></p>
    <!-- 其他信息 -->
    <p>
        <?php  if(!empty($val[&#39;child&#39;])) { ?>
        <?php  foreach($val[&#39;child&#39;] as $k=>$v) ?>
        </p><p>
            </p><h2><?php  echo $v[&#39;user_name&#39;];?></h2>
            <p><?php  echo $v[&#39;comm_cont&#39;] ?></p>
            <!-- 其他信息 -->
        
        <?php  }}?>
    

<?php  } ?>
At the same time, the formed reply style is as follows:

PHP: Create an Infinitus comment module

snipaste20170105_204906.png

The Infinitus reply with similar comment structure is completed.

PS

This is just a form of comment. If there is a staircase-like structure, this implementation is simpler, as shown below:

PHP: Create an Infinitus comment module

Stairway comment structure

This structure is easy to complete, as long as the parent_id in the storage database is completely equal to the comm_id you replied to, after the following process Infinitus classification can be completed.

/**
 * 子孙树
 */
function getSubTree($data , $parent , $son , $pid = 0, $lev = 0) {
    $tmp = array();
    foreach ($data as $key => $value) {
        if($value[$parent] == $pid) {
            $value['lev'] = $lev;
            $tmp[] = $value;
            $tmp = array_merge($tmp , getSonTree($data , $parent , $son , $value[$son] , $lev+1));
        }
    }
    return $tmp;
}
This kind of infinite descendant tree classification is different from the descendant tree classification given earlier. After classification, the subclasses will not be wrapped in children, but will form a hierarchy, with the highest level being 0, and going down in sequence.

For example: the comm_id=1, parent_id=0 of the first-level comment, then the comm_id=2, parent_id=1 of the second-level comment; the comm_id=3, parent_id=2 of the third-level comment;

The classification finally forms the following structure

array(
array('comm_id'=>1,parent_id=>0,art_id=>1,'lev'=>0) ,
array('comm_id'=>2,parent_id=>1,art_id=>1,'lev'=>1),
array('comm_id'=>3,parent_id=>2,art_id=>1,'lev'=>2),
array('comm_id'=>4,parent_id=>3,art_id=>1,'lev'=>3),
array('comm_id'=>5,parent_id=>2,art_id=>1,'lev'=>2)
);

然后直接循环输出,并将lev作为属性打印在html中,最后利用js读取lev,并根据不同的等级分配不同的margin-left即可,它会随着margin的不同而排列在不同的位置,如下:

// html中
<?php  foreach($tree as $key=>$val) {?>
<p>">
……
</p>
<?php  } ?>

// js中
$('p.comm_list').css('margin-left' , 20 * lev);


Attribute
KEY AUTO_INCREMENT
NULL DEFAULT 0

time Comment Post time

The above is the detailed content of PHP: Create an Infinitus comment module. 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's Purpose: Building Dynamic WebsitesPHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP: Handling Databases and Server-Side LogicPHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

How do you prevent SQL Injection in PHP? (Prepared statements, PDO)How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AM

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.

PHP and Python: Code Examples and ComparisonPHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP in Action: Real-World Examples and ApplicationsPHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: Creating Interactive Web Content with EasePHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AM

PHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.

PHP and Python: Comparing Two Popular Programming LanguagesPHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

The Enduring Relevance of PHP: Is It Still Alive?The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

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)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools