473,763 Members | 5,466 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

PHP / MySQL Threaded Discussion: One Query

I'm attempting to create a threaded comment system involving PHP /
MySQL. Currently, I have a table called comments which looks like:

Table Comments: (comment_id, comment_root_id , comment_parent_ id, text,
datetime_create d).

Most of the tutorials that I've found online discuss how to thread the
results from the database with recursive query calls. This is all to
the good; however, with lengthy discussion, this solution becomes slow
and unacceptable.

Is there a way to retrieve all the comments from the database in one
query (e.g. SELECT * FROM comments WHERE comment_root_id = $id) and
then to do the ordering/threading in php with some function (i'm
guessing recursive to handle infinite depths)?

What would such a function look like?

I found a function online that recurses through an array. Perhaps
something like this could be modified to thread the comments?

///============
//Sample thread
$thread_info_ar r['message_id'] = array(154, 155, 156, 157, 161, 163);
$thread_info_ar r['reply_id'] = array(0, 154, 155, 154, 155, 157);
$thread_info_ar r['message_title'] = array('Post 154 (initial post)',
'Post 155 (reply to post 154)', 'Post 156 (reply to post 155)', 'Post
157 (reply to post 154)', 'Post 161 (reply to post 155)', 'Post 163
(reply to post 157)');
$thread_info_ar r['date_posted'] = array('2004-06-01', '2004-06-02',
'2004-06-03', '2004-06-04', '2004-06-05', '2004-06-06');

$iteration = 0;

reord_thread($t hread_info_arr['message_id']);

function reord_thread(&$ data)
{
global $thread_info_ar r, $iteration;

if (is_array($data ))
{
array_walk($dat a, 'reord_thread') ;
}
else
{
echo 'Date: ' . $thread_info_ar r['date_posted'][$iteration] . ' Title:
' . $thread_info_ar r['message_title'][$iteration] . '<br>';
$iteration++;
}
}
///============

Thanks in advance. Any help would be greatly appreciated. Enjoy your
day.
Jul 17 '05 #1
5 5201
You're close.

Have a look at my large post about this I made a year or so ago (Bless
Google ;)).

http://groups.google.com.au/groups?q...ine.net&rnum=1

It's an example with code.

Other threads of interest:
http://groups.google.com.au/groups?h...line.net#link1
http://groups.google.com.au/groups?h...erlin.de#link1

Cheers.

ensnare wrote:
I'm attempting to create a threaded comment system involving PHP /
MySQL. Currently, I have a table called comments which looks like:

Table Comments: (comment_id, comment_root_id , comment_parent_ id, text,
datetime_create d).

Most of the tutorials that I've found online discuss how to thread the
results from the database with recursive query calls. This is all to
the good; however, with lengthy discussion, this solution becomes slow
and unacceptable.

Is there a way to retrieve all the comments from the database in one
query (e.g. SELECT * FROM comments WHERE comment_root_id = $id) and
then to do the ordering/threading in php with some function (i'm
guessing recursive to handle infinite depths)?

What would such a function look like?

I found a function online that recurses through an array. Perhaps
something like this could be modified to thread the comments?

///============
//Sample thread
$thread_info_ar r['message_id'] = array(154, 155, 156, 157, 161, 163);
$thread_info_ar r['reply_id'] = array(0, 154, 155, 154, 155, 157);
$thread_info_ar r['message_title'] = array('Post 154 (initial post)',
'Post 155 (reply to post 154)', 'Post 156 (reply to post 155)', 'Post
157 (reply to post 154)', 'Post 161 (reply to post 155)', 'Post 163
(reply to post 157)');
$thread_info_ar r['date_posted'] = array('2004-06-01', '2004-06-02',
'2004-06-03', '2004-06-04', '2004-06-05', '2004-06-06');

$iteration = 0;

reord_thread($t hread_info_arr['message_id']);

function reord_thread(&$ data)
{
global $thread_info_ar r, $iteration;

if (is_array($data ))
{
array_walk($dat a, 'reord_thread') ;
}
else
{
echo 'Date: ' . $thread_info_ar r['date_posted'][$iteration] . ' Title:
' . $thread_info_ar r['message_title'][$iteration] . '<br>';
$iteration++;
}
}
///============

Thanks in advance. Any help would be greatly appreciated. Enjoy your
day.

Jul 17 '05 #2
Hello,
I read a tutorial on another way to store "trees". Hmmmm... It was
called "interval representation" from what I gather. You can read a full
tutorial (in French, sorry) there :
http://sqlpro.developpez.com/Tree/SQL_tree.html

A bit more complex, but apprently efficient.

HTH, BR,
Damien
Jul 17 '05 #3
en*****@gmail.c om (ensnare) emerged reluctantly from the curtain
and staggered drunkenly up to the mic. In a cracked and slurred
voice he muttered:
Most of the tutorials that I've found online discuss how to
thread the results from the database with recursive query calls.
This is all to the good; however, with lengthy discussion, this
solution becomes slow and unacceptable.


I use a system which is simple and doesn't rely on recursion. I
basically store the entire thread "path" as a row field.

So basically I would have the following table structure:

ID | Name | Path
----+-------------------------+----------
0 | Category One | 00
1 | Sub-category of cat one | 00_01
2 | Sub-cat of cat id #1 | 00_01_02
3 | Category Two | 00
4 | Category Three | 00
5 | Sub-cat of cat three | 00_04
6 | Sub-sub cat of cat #3 | 00_04_05

Want to get the entire tree structure? Just do an ORDER BY on the
path column and use some PHP code like the following for
formatting:

while ($result = mysql_fetch_ass oc($query)) {
$nesting_depth = count(explode(" _", $result['category_path']));
$branch = str_repeat("--", $nesting_depth) ;
echo "| $branch {$result['name']}";
}

This should result in:

| Category One
| -- Sub-category of cat one
| ---- Sub-cat of cat id #1
| Category Two
| Category Three
| -- Sub-cat of cat three
| ---- Sub-sub cat of cat #3

Want to get a particular tree branch? Just run a "SELECT * FROM
table WHERE path LIKE '00_01%' ORDER BY path ASC" query.

How you choose to store the path field data is up to you. I'm using
this type of system for a photo gallery system and so far it's
working fine.

--
Phil Roberts | Without me its just aweso. | http://www.flatnet.net/

"Mankind differs from the animals only by a little,
and most people throw that away."
- Confucious
Jul 17 '05 #4
Hi,

On 27 Jun 2004 23:43:23 -0700, en*****@gmail.c om (ensnare) wrote:
I'm attempting to create a threaded comment system involving PHP /
MySQL. Currently, I have a table called comments which looks like:

Table Comments: (comment_id, comment_root_id , comment_parent_ id, text,
datetime_creat ed).

Most of the tutorials that I've found online discuss how to thread the
results from the database with recursive query calls. This is all to
the good; however, with lengthy discussion, this solution becomes slow
and unacceptable.


Its a bit long to explain out of the box, but look up "nested set
model", which is well described in books of Joe Celko. It needs only
one self referencing query for a whole tree (discussion)

HTH, Jochen
--
Jochen Daum - Cabletalk Group Ltd.
PHP DB Edit Toolkit -- PHP scripts for building
database editing interfaces.
http://sourceforge.net/projects/phpdbedittk/
Jul 17 '05 #5
In article <om************ *************** *****@4ax.com>, Jochen Daum wrote:
Hi,

On 27 Jun 2004 23:43:23 -0700, en*****@gmail.c om (ensnare) wrote:
I'm attempting to create a threaded comment system involving PHP /
MySQL. Currently, I have a table called comments which looks like:

Table Comments: (comment_id, comment_root_id , comment_parent_ id, text,
datetime_crea ted).

Most of the tutorials that I've found online discuss how to thread the
results from the database with recursive query calls. This is all to
the good; however, with lengthy discussion, this solution becomes slow
and unacceptable.


Its a bit long to explain out of the box, but look up "nested set
model", which is well described in books of Joe Celko. It needs only
one self referencing query for a whole tree (discussion)


And when you've read that, surf to
http://pear.php.net/package/DB_NestedSet and find an implementation ;)

--
Tim Van Wassenhove <http://home.mysth.be/~timvw>
Jul 17 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
478
by: Gary L. Burnore | last post by:
REQUEST FOR DISCUSSION (RFD) unmoderated group comp.databases.mysql This is an invitation to discuss the following proposal to create newsgroup comp.databases.mysql. Please note that YOU CANNOT VOTE NOW; you may be able to vote on a version of this proposal later. See the PROCEDURE section below if you need information about how the discussion works. PLEASE POST ANY FOLLOWUPS TO THE NEWSGROUP NEWS.GROUPS.
8
2689
by: William Drew | last post by:
REQUEST FOR DISCUSSION (RFD) unmoderated group comp.databases.mysql This is an invitation to discuss the following proposal to create newsgroup comp.databases.mysql. Please note that YOU CANNOT VOTE NOW; you may be able to vote on a version of this proposal later. See the PROCEDURE section below if you need information about how the discussion works. PLEASE POST ANY FOLLOWUPS TO THE NEWSGROUP NEWS.GROUPS.
0
4932
by: Ganbold | last post by:
Hi, I'm new to multi-threaded programming and reading the book "Programming with POSIX Threads" and trying to understand concepts and coding. What I'm trying to do is to rewrite mysql client application (which calculates ISP dial-up customers' billing) into multi-threaded version.
5
5139
by: Boo | last post by:
Can someone explain to me why this simple query will not use an index on the field confirm_date? select * from comments where confirm_date != 0 confirm_date is an integer, and I have a regular index on it. When I use EXPLAIN it shows all 1233 rows being searched with NULL for the possible keys. Thanks for your help.
33
5593
by: Joshua D. Drake | last post by:
Hello, I think the below just about says it all: http://www.commandprompt.com/images/mammoth_versus_dolphin_500.jpg Sincerely, Joshua Drake
2
2255
by: Chris | last post by:
I think I already know that the answer is that this can't be done, but I'll ask anyways. Suppose you want to use an RDBMS to store messages for a threaded message forum like usenet and then display the messages. A toy table definition (that I've tried to make standards compliant) might look like: create table messages ( message_id integer,
2
2255
by: Adrienne Boswell | last post by:
The threaded discussion scripts I have found so far all use nested tables (yuk!). Other message type scripts do not show a threaded structure, and I think that's really important. So, let's see, start with (it should also be able to be sorted by author or date): <table> <thead> <th>Message</th><th>Author</th><th>Date</th>
9
2000
by: Derrick Shields | last post by:
I'm working with a database that has over 11 million rows. The .SQL drop file is about 2.5gigs. Doing a simple query: select * from people where last_name like '%smith%' A query like this can take up to two minutes. I've spent hours reading these forums and other sites on the internet, and I've figured that I need to do a couple things: create some indexes -and- possibly create some partitions
30
2838
by: Einstein30000 | last post by:
Hi, in one of my php-scripts is the following query (with an already open db-connection): $q = "INSERT INTO main (name, img, descr, from, size, format, cat, host, link, date) VALUES ('$name', '$img', '$descr', '$user', '$size', '$format', '$cat', '$host', '$link', '$date')" or die(mysql_error()); And when the query gets executed i get back the following error:
0
9387
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10002
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9823
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8822
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5270
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5406
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3917
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3528
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2794
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.