0

Image Table enter image description here

Hello i have a table comments and i need to take the last three comments but another way like this:

8
9
10

My code show this:

10
9
8

Code:

$sql_query = $connection->query("SELECT * FROM comments WHERE `post_id` = '38' ORDER BY `id` DESC LIMIT 3");

while ($ff = $sql_query->fetch_array(MYSQLI_ASSOC)) {
    echo $ff["text"]. "</br>";
}

Thanks in advance !

15
  • Wrap your statement in a subquery and resort it, in ascending order, by comment ID. Commented Dec 26, 2016 at 21:36
  • Changing 'DESC' to 'ASC' will make it work i guess. Commented Dec 26, 2016 at 21:37
  • @Terry please show me the code Commented Dec 26, 2016 at 21:38
  • 1
    @Fred-ii- Interesting. In this particular case, I think the easiest way is to reverse the set with PHP but indeed if the count of rows is known limit with an offset is a super clean way of doing it. However I don't know if it is possible to count the rows as a subquery and use it as offset, all in one query. Just posted a question about that. Commented Dec 26, 2016 at 22:30
  • 1
    @sidyll doubly interesting comment there. I'll keep an eye out on your question, cheers Commented Dec 26, 2016 at 22:31

2 Answers 2

2

You can do it with a subquery, as described in this question. However it might be easier to just use PHP's array_reverse():

$rows = array_reverse($sql_query->fetch_all(MYSQLI_ASSOC));
foreach ($rows as $ff)
    echo $ff["text"]. "</br>";

With the subquery, if you wish:

SELECT * FROM (
  SELECT * FROM comments
  WHERE `post_id` = '38'
  ORDER BY `id` DESC LIMIT 3
) t ORDER BY t.id

Basically this creates a derived table aliased to t with the result of your original query, and reorders this limited set of results.

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

1 Comment

I'll have to remember about that array_reverse(). I've never used it before but might in the future.
0

Following query will give your desider output

select * from (SELECT * FROM comments WHERE `post_id` = '38' ORDER BY `id` DESC LIMIT 3) temp order by id

Comments

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.