Immediately make a reservation that I am not a professional web developer, but I’m doing this just for fun, as well as for self-development.
It took to implement in my development the possibility of commenting. Simple comment structures do not interest me anymore, so I wanted a
tree .
At first I tried to implement it myself, but then I decided to turn to Internet resources for
drawings of invented wheels )))
The most interesting resources that catches my eye (
1 ,
2 ,
3 ,
4 ) can be read for general development.
As a rule, most of the proposed ideas require significant changes to the existing databases and application logic.
Therefore, I decided to take up the
invention of the wheel of its original form . Unfortunately, I did not manage to provide stable and correct work on the output of tree comments only with the help of server scripts and databases. But it turned out differently ...
The idea came, as always, suddenly. To display a full comment tree, it took (in my case):
- MySQL table with the following field names: id (int), parent (int), author (text), comment (text). The first field is a unique comment id, the second is parent — the id of the parent comment, the third is author — the name of the commentator, the fourth is comment — the comment itself.
- Php
- A browser with JavaScript enabled and aware of the DOM. About DOM you can read here: http://javascript.ru/start/dom/intro
How to get data from the database tables speak nebudu, go straight to the php-function output comment (in the form above):
function show_comment($id,$parent,$author,$comment) {
echo "<div id='comment$id'>$author: $comment</div>";
}
You can get around the parameters passed by looking at the proposed table structure.
Then, calling this function for each comment from the database, pass this list (unordered!) To the browser.
Now the fun part. The browser itself is able to place the comments in the "tree". To do this, it is necessary to call the javascript function on the user’s side, passing it two parameters — the comment id, and parent — the parent id:
')
document.getElementById("comment"+parent).appendChild(document.getElementById("comment"+id));
If the comment does not have a parent (parent = 0), then it will be the root.
Thus, comments will be placed in the tree by the user's browser, which will reduce the load from the server and simplify the structure of the database and server scripts. But this increases the load on the browser, so you have to choose ...