Solved

PHP While Loop Last Row

Posted on 2013-10-28
7
1,231 Views
Last Modified: 2013-10-29
I'm using mysqli to return some results and echo'ing them out.  How can I tell when I've reached the last result?  I'm separating my results with commas and don't want the comma after the last result.
0
Comment
Question by:N R
  • 3
  • 2
  • 2
7 Comments
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39607122
Please show us your code so can help you and not guess what you're doing.
0
 
LVL 11

Author Comment

by:N R
ID: 39607128
Sure:

//Pull the tags
            $sql3="select tag from tags where isproject = 1 and project_id = ".$projectid;
            $result3 = $db->query($sql3);
            echo 'Project Tags: ';
            while($row3 = $result3->fetch_array())
            {
                echo $row3['tag'].',';
            }
            ?>

Open in new window

0
 
LVL 83

Expert Comment

by:Dave Baldwin
ID: 39607158
This should work.
//Pull the tags
  $sql3="select tag from tags where isproject = 1 and project_id = ".$projectid;
  $result3 = $db->query($sql3);
  echo 'Project Tags: ';
  $count = 0;
  while($row3 = $result3->fetch_array())
    {
    if($count++) echo ', ';
    echo $row3['tag'];
    }
  ?>

Open in new window

0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 110

Expert Comment

by:Ray Paseur
ID: 39607198
The while() loop stops after the last row of the query results set.  Here is how I might do it.  There are literally dozens of solutions!

// CREATE THE OUTPUT VARIABLE
$out3 = 'Project Tags: ';

// RUN THE QUERY AND GET THE RESULTS SET
$sql3 = "SELECT tag FROM tags WHERE isproject = 1 AND project_id = '$projectid'";
$res3 = $db->query($sql3);
while($row3 = $result3->fetch_object())
{
    $arr3[] = $row3->tag;
}
// ADD THE TAGS TO THE OUTPUT VARIABLE
$out3 .= implode(', ', $arr3);

echo $out3;

Open in new window

0
 
LVL 11

Author Comment

by:N R
ID: 39607606
It looks like the easiest to modify would be DavidBaldwin's solution.

I'm curious though so I can use this in the future.

You set $count = 0 out of the loop.  Then within the loop I don't get the if($count++), what is that doing?  Not sure how it ties to the result set to see how many records are left?
0
 
LVL 83

Accepted Solution

by:
Dave Baldwin earned 250 total points
ID: 39607879
if($count++) checks to see if $count is not 0 and then it increments it.  The first time thru it will be zero so no comma will be printed.  Every other time after that it will echo a comma before the next item.  When the last item is fetched, the loop will not be executed anymore.

Same as doing it this way:
//Pull the tags
  $sql3="select tag from tags where isproject = 1 and project_id = ".$projectid;
  $result3 = $db->query($sql3);
  echo 'Project Tags: ';
  $count = 0;
  while($row3 = $result3->fetch_array())
    {
    if($count) echo ', ';
    $count = $count + 1;
    echo $row3['tag'];
    }
  ?>

Open in new window

0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
ID: 39608364
@Gallitin, I'd like to gently point you in the direction of a better understanding, and of finding the problem.  The problem occurs because your script is using echo the wrong way.  This is a code smell and it causes difficult problems such as "don't want the comma after the last result."  For better or worse, PHP is a very permissive language and it allows us to do things that do not always make sense.

Think about it for a moment... The script explicitly says echo $row3['tag'].',';.  There is the comma, and it's both the comma that you want (to separate data elements) and the comma that you don't want at the end!  A single line in the script does two things, and you don't want one of those things.  Almost every time we have a line of code that is doing two or more things we have a potentially troublesome bit of programming.  It follows that the correct way to think about this situation is to home in on that particular line of code and see why it's doing two things instead of one thing.    And we can find the answer in the concatenation operator (the "dot" or "period"), where we take the array element, then concatenate the comma to the end of it before writing it to the browser output stream.

We have one thing we want every time: $row3['tag'].  And we have one thing we want some of the time, but do not want every time: ','.  So the challenge is to separate the creation of these two things.  

You can accomplish that in many different ways, but once your script has executed the echo statement, you can't get the data back; it's gone to the browser irrevocably.  If you think about that for a moment, you'll probably conclude, as many professional programmers have, that you want to use the echo statement very sparingly.  Before you use echo, you can create any kind of data structure you want.  That is why I created an array of "tag" elements, then bound them together with the comma separator in the implode() statement.  It's something I've done about a thousand times before, because comma-separated lists are one of the very common data constructs we encounter in web programming.

There are many ways to get what you want.  You can count up the elements as DaveBaldwin shows.  You can get the count from $res3->num_rows and decrement it.  You can use implode() to insert the commas as the "glue" argument.  And there are other ways, too, for example, by using rtrim() to remove the unwanted characters from the end of the string.  

What all of these designs have in common is this: they only send to the browser the exact data you want, not the data you don't want.
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
This article discusses four methods for overlaying images in a container on a web page
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

713 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question