简体   繁体   中英

Need help in displaying last 5 rows. PHP, MYSQL

Can anyone tell me what am I doing wrong. I would like to display the last 5 rows in desc order.

$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id desc       limit 0,5") 
or die(mysql_error());  
while($row = mysql_fetch_array( $pull_activity_logs )) {
$activity_time = $row["datetime"];
$activity = $row["activity"];
}
echo "$activity";

Help would be deeply appreciated

Well, you can always select the first five in asc order, that would be last five in desc order, and then you could reverse their order in php if needed (5 values isnt anything what an array couldn't handle)

CODE:

$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id asc limit 5"); 
$temp_arr = array();
while($row = mysql_fetch_array( $pull_activity_logs )) {
  $temp_arr[] = $row; //add to end
}
$final_arr = array_reverse($temp_arr);
foreach($final_arr as $row) //this doesn't have to be named $row
  $activity_time = $row["datetime"];
  $activity = $row["activity"];
  echo "$activity";
}

EDIT:

now when i look at it maybe whole problem was in wring position of your echo:

$pull_activity_logs = mysql_query("SELECT * FROM activity_logs WHERE ac_no = '$logined_acc' order by id desc limit 0,5") 
or die(mysql_error());  
while($row = mysql_fetch_array( $pull_activity_logs )) {
  $activity_time = $row["datetime"];
  $activity = $row["activity"];
echo "$activity"; //this goes INSIDE the loop
}

You can retrieve the first five in ascending order and then order them in SQL by using a subquery:

select al.*
from (SELECT al.*
      FROM activity_logs al
      WHERE ac_no = '$logined_acc'
      order by id asc
      limit 0, 5
     ) al
order by id desc;

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