Reputation: 2564
while($data=$SQL->fetch(PDO::FETCH_ASSOC)){
echo $data=['message'];
}
is that possible to reverse while loop? I have a page echo out messages and I need put in reverse
SQL- DESC LIMIT 20 fetch last 20 messages
but my chat box is print in reverse
message 1 (oldest message)
message 2
message 3 (newest message)
Upvotes: 0
Views: 3867
Reputation: 25993
You should define the order of the data set in your original SQL query.
See documentation for the ORDER BY clause.
Update
It seems that the OP wants the 20 newest messages, but ordered in reverse. Then you need to perform a subquery like this:
SELECT `message`
FROM (SELECT * FROM `table`
ORDER BY `id` DESC
LIMIT 20) AS `i`
ORDER BY `i`.`id` ASC;
Upvotes: 3
Reputation: 4519
If you really want to reverse the data in PHP, you can use array_reverse
:
// Fetch all records
$data = $SQL->fetchAll(PDO::FETCH_ASSOC);
// Reverse them
$data = array_reverse($data);
foreach ($data as $record) {
echo $record['message'];
}
Although I would recommend ordering in SQL, as it will be faster.
Upvotes: 0
Reputation: 1048
After fetching records You can just reverse your returned array
https://www.php.net/array_reverse
Upvotes: 1