GA ASD
GA ASD

Reputation: 1

PHP: MYSQL QUERY Ordery By

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 !

Upvotes: 0

Views: 37

Answers (2)

sidyll
sidyll

Reputation: 59277

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.

Upvotes: 2

reza
reza

Reputation: 1507

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

Upvotes: 0

Related Questions