Solved

PHP While Loop Last Row

Posted on 2013-10-28
7
1,131 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 82

Expert Comment

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

Author Comment

by:N R
Comment Utility
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 82

Expert Comment

by:Dave Baldwin
Comment Utility
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
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 82

Accepted Solution

by:
Dave Baldwin earned 250 total points
Comment Utility
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 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 250 total points
Comment Utility
@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 Gift Card with Acronis Backup Purchase!

Backup any data in any location: local and remote systems, physical and virtual servers, private and public clouds, Macs and PCs, tablets and mobile devices, & more! For limited time only, buy any Acronis backup products and get a FREE Amazon/Best Buy gift card worth up to $200!

Join & Write a Comment

As a database administrator, you may need to audit your table(s) to determine whether the data types are optimal for your real-world data needs.  This Article is intended to be a resource for such a task. Preface The other day, I was involved …
Does the idea of dealing with bits scare or confuse you? Does it seem like a waste of time in an age where we all have terabytes of storage? If so, you're missing out on one of the core tools in every professional programmer's toolbox. Learn how to …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

771 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now