Solved

PHP While Loop Last Row

Posted on 2013-10-28
7
1,212 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
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 109

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 109

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

What is SQL Server and how does it work?

The purpose of this paper is to provide you background on SQL Server. It’s your self-study guide for learning fundamentals. It includes both the history of SQL and its technical basics. Concepts and definitions will form the solid foundation of your future DBA expertise.

Question has a verified solution.

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

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 …
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

856 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