Wordpress - First and last result of wp_query


/ Published in: PHP
Save to your folder(s)

I needed to know the first time a user took a quiz and the last quiz they took. I utilized php count() and as I iterated through the array, I incremented a variable ($i) which before the loop, I already set it to 1. If $i was equal to 1, I printed it out. If I was equal to the total count, I printed it out. Everything else got ignored.


Copy this code and paste it in your HTML
  1. $firstQuizSql = $wpdb->get_results("SELECT id, datetaken, person FROM aw_wpsqt_all_results WHERE person_name='$user_info->user_login' ORDER BY id");
  2. $i = 1;
  3. foreach ($firstQuizSql as $firstQuizResult) {
  4. //first quiz result
  5. if ($i == 1) {
  6. echo $firstQuizResult->id . " ";
  7. }
  8.  
  9. //last quiz result
  10. if ($i == count($firstQuizSql)) {
  11. echo $firstQuizResult->id . " ";
  12. }
  13.  
  14. $i++;
  15. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.