Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1448
  • Last Modified:

PHP While Loop Last Row

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
Nathan Riley
Asked:
Nathan Riley
  • 3
  • 2
  • 2
2 Solutions
 
Dave BaldwinFixer of ProblemsCommented:
Please show us your code so can help you and not guess what you're doing.
0
 
Nathan RileyFounder/CTOAuthor Commented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
Ray PaseurCommented:
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
 
Nathan RileyFounder/CTOAuthor Commented:
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
 
Dave BaldwinFixer of ProblemsCommented:
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
 
Ray PaseurCommented:
@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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 3
  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now