Monday, May 27, 2013

AJAX Multi-Level Comments

In this tutorial we will create multi level comments. You must have seen comments on youtube and that they have levels depending on who replied to who. That’s exactly what we will build.

Intro
I’ve seen that most of scripts online execute query to check if comment has child elements. Let’s say you have 10 comments and each of them has 1 child element. You would execute 1 query to get all those 10 comment (first level) and then for each of them to check if it has child. And then for each child to check if that comment has childs to. That would be 1 + 10 + 10 = 21. That’s 21 query for nothing. It’s easier to do it with just one query that will load all comments and then to structure them in an multidimensional array. For that purpose we will use walker class that you can download here and read tutorial how we made ithere. So let’s start working on it.

Folder Structure
Folder structure is very simple. jQuery folder has jQuery v1.3.2. We have two image files used for loader and to style comments. In our lib folder we have walker class that I mentioned before and we have some php file that we’ll later talk about.

Muti Level Comments Folder Structure

Muti Level Comments Folder Structure

MySQL Table
We’ll have very simple MySQL table. Table will have 7 fields.

    id – unique ID
    name – name of comment author
    email – e-mail of comment author
    url – url of comment author (optional)
    parent – ID of parent comment (if no parent then equals to 0)
    date – date that comment was posted
    message – comment message

Source

01.CREATE TABLE IF NOT EXISTS `comments_tutor` (

02.`id` int(11) NOT NULL AUTO_INCREMENT,

03.`name` varchar(128) COLLATE utf8_bin NOT NULL,

04.`email` varchar(255) COLLATE utf8_bin NOT NULL,

05.`url` varchar(255) COLLATE utf8_bin NOT NULL,

06.`parent` int(11) NOT NULL DEFAULT '0',

07.`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,

08.`message` text COLLATE utf8_bin NOT NULL,

09.PRIMARY KEY (`id`)

10.) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=1 ;

You can download source file here or check demo here. Thank you for reading.

No comments:

Post a Comment