Reputation: 365
I want to make only one level deep comments system in php just like stackoverflow comments system.
i have created a comments table with the following fields
comment_id int(11) (PRIMARY KEY)
parent_id int(11)
thread_id int(11) (FOREIGN KEY)
title varchar(400)
body varchar(400)
date_comment timestamp
user_name varchar(100)
I am retrieving the parent comments with this query
SELECT * FROM comments WHERE thread_id = {$thread_id}
AND parent_id IS NULL
But I also need to retrieve all the children comments as well in the order that first come parent comment then all of its child comments and so on.. (Just Like Stackoverflow comment system)
Any Suggestion??
Upvotes: 0
Views: 449
Reputation: 2210
Assuming you only record comments in the comments table...
To fetch all comments of a thread use an sql query like that:
select * from comments where thread_id = 'yourthread_id'
I assume the q & a as parent.
You must write the comments with their thread and parent id's to table, recording where they belong.
Do not leave them null while recording.
So:
$query = "select * from comments where thread_id = '$threadId'";
$result = mysqli_query($query);
if(!$result){
echo('Failure : '.mysqli_errno());
exit(0);
}
$comments = [];
while(true){
$row = mysqli_fetch_assoc($result);
if(!$row)break;
$comments[] = $row;
}
now you have $comments array filled with comments belonging to that thread.
Every element has the structure of your database record:
$comment[0]['comment_id'] etc...
Now by traversing that array you can collect each comment into its appropriate parent via its parent_id, and discover their entry order via the timestamp... That is array manipulation and I guess you can do it easily.
Upvotes: 0
Reputation: 3823
You can't order all data without any special key for it.
The easiest way is select all comments and threads with:
SELECT
*
FROM
comments
WHERE
thread_id = {$thread_id}
and do simple manipulation with result array:
$array = array();
foreach($result as $row)
{
if(!$row['thread_id']){
$array[$row['id']]=array();
$array[$row['id']]['DATA'] = $row;
continue;
}
$array[$row['id']][$row['id']] = $row;
}
You will have array like:
Array(
/*thread==>*/ [11] => Array(
/*thread data==>*/ [DATA] => Array(/*with thread data*/)
/*comment==>*/ [12] => Array(/*with data*/)
/*comment==>*/ [13] => Array(/*with data*/)
)
)
Upvotes: 2
Reputation: 2484
<?php
$a = mysql_query("Select * From comments where thread_id = {$thread_id} AND parent_id IS NULL");
while($row= mysql_fetch_array($a)) {
$b = mysql_query("Select * From comments, where thread_id = ($thread_id} AND parent_id = " . $row['comment_id'] .";");
while($row2 = mysql_fetch_array($b) {
}
}
Upvotes: 0