Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

PHP While Loop Last Row

Posted on 2013-10-28
7
Medium Priority
?
1,394 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:Nathan Riley
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 2
  • 2
7 Comments
 
LVL 84

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 12

Author Comment

by:Nathan Riley
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 84

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
What Is Blockchain Technology?

Blockchain is a technology that underpins the success of Bitcoin and other digital currencies, but it has uses far beyond finance. Learn how blockchain works and why it is proving disruptive to other areas of IT.

 
LVL 111

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 12

Author Comment

by:Nathan Riley
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 84

Accepted Solution

by:
Dave Baldwin earned 1000 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 1000 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

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

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

This post contains step-by-step instructions for setting up alerting in Percona Monitoring and Management (PMM) using Grafana.
By, Vadim Tkachenko. In this article we’ll look at ClickHouse on its one year anniversary.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

722 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