简体   繁体   中英

Hierarchical message/reply in PHP and MySQL

I am building a message/reply application. The idea is to have a message displayed and any replies are displayed directly below it in hidden divs with the text "show message from ...".

I don't have any problem with the layout itself and have that working fine, but what I am unsure of, is how to return a single message with multiple replies. The SQL query below is what I have to date, but this will return all the replies, but also repeats the main message for each reply.

My question is, how can I return the main message once, and the all the associated replies?

SELECT u.userid, u.first, u.last, c.title, c.body, c.messid, 
   c.adddate, ru.first, ru.last, cr.body, cr.messreplyid 
FROM chat c INNER JOIN users u on u.userid = c.userid 
 LEFT JOIN chat_reply cr on cr.messid = c.messid 
 LEFT JOIN users ru on ru.userid = cr.userid 
WHERE c.messid =".$_GET['messid']." 
GROUP BY cr.messreplyid"


u.userid = the original posters primary key
u.first + u.last = the original posters name
c.title = the title of the post
c.body = the message body
c.messid = the message primary key
c.adddate = message timestamp
ru.first + ru.last = the name of the person who replied
cr.body = the the reply message body
cr.messreplyid = the reply primary key

As I said, I seem to get two results, one will show a single message with a single reply(if I don't use the group by) or all the replies but repeats the message. I'm sure this can be done with a complex query, such as a select within a select, but would be grateful for any help.

The child posts need to reference their parent posts with something else than the primary key. What you are doing in the JOIN won't work because the primary key is always different.

For example, if the messreplyid of the children contained the messid of the parent, you could do LEFT JOIN chat_reply cr on cr.messreplyid = c.messid

Don't do grouping or you'll get only one reply.

And please, for the love of god, don't use an unsanitized $_GET variable when putting together an SQL statement! You'll open yourself up to SQL injections!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM