0

I have a discussion type page, where users can enter their replies on different subjects. For this, I have a table name replies with fields replyID, topicID, userID, replybody, time

On the page, where I display the result, I use this php command:

$run = mysql_query("SELECT * FROM replies WHERE topicID = $topicnumber ORDER BY time DESC Limit 5");

while($data= mysql_fetch_array($run)){
// do formatting and display data 
}

as you can see, the page initially displays only 5 replies on a topic (after which, if interested, user clicks to visit the page where all replies are displayed).

the thing is, the above code displays correctly the recent 5 replies, but I want to change the order of its display. It shows the recent most reply on top, and older replies are displayed as we go down, but I want to change this order, showing the recent most reply on bottom.

I think I'm missing a very simple point here, since most of the website have this feature where recent most comments go down, but hey, "no question is small".

0

2 Answers 2

2

I don't think that's very easy in sql.

I would just load the results in an array and use array_reverse() to reverse the order. Then you can loop through the array and display the values like you do now.

Otherwise I think you need to do 2 queries, one to get the total amount and then one to limit your result set to the last x items.

Sign up to request clarification or add additional context in comments.

Comments

0

Use a nested query to reverse the order in SQL:

SELECT *
FROM (
    SELECT * FROM replies WHERE topicID = $topicnumber ORDER BY time DESC Limit 5
) AS a
ORDER BY time ASC

The inner query will return your most recent 5 records, while the outer query will reverse the sort order of those 5.

5 Comments

Thanks Marc B, You saved the Day! :)
here is another one, how can I use SQL_CALC_FOUND_ROWS within this query, if I also want to get the total number of replies made on that topic?
not sure if you can. you'd have to use it on the inner query, but the outer query will be the last one executed, and it won't have a limit, so the found_rows would be 0. e.g you'd have to run the query twice. once for the actual results, and once to calculate the total rows. at least if you do select count(*) ... it'll be relatively fast since it won't be retrieving row-level data
yes, I did the same. SQL_CALC_FOUND_ROWS returns only the limit the inner query generated, so returned to SELECT COUNT
'course, since you're only fetching 5 rows of data in the inner query, you'd be better off fetching into a php array and displaying that in reverse order. that'd save you the second query to get the count().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.