0

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

3
  • 1
    I know this doesn't solve your problem, but I highly disencourage you of using mysql_query() - just like PHP guys does in here: php.net/manual/en/function.mysql-query.php - it's deprecated as of PHP 5.5.0 and will be removed in the future Commented Sep 1, 2013 at 19:20
  • Probably a typo in the query? check also if $logined_acc is actually defined, the query syntax is ok Commented Sep 1, 2013 at 19:26
  • I don't know what kind of problem you are facing? echo "$activity"; statement is outside of loop. you will see always last value of 5. Commented Sep 1, 2013 at 19:32

2 Answers 2

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

That or use concatenation assignment .= on $activity. And initialize it before the loop.
0

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;

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.