Welcome to WebmasterWorld Guest from 54.224.57.95

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

How to in a while statement

     
4:33 pm on Nov 17, 2011 (gmt 0)

5+ Year Member



Hello all, I have a quick question my logic doesn't seem to resolve on its own

Say I have a while loop getting data from a DB and I have anywhere from 2 to hundreds of results, how can I make an exception between the first and second result to display something like an add?

It would be like this:

-- Result 1 --
-- ADD --
-- Result 2 --
-- Result 3 --
-- and so on --

Taking also into consideration that I am sorting this results in the form of:

ORDER BY `date` DESC

Let me know if you need some clarification, thanks :)
4:45 pm on Nov 17, 2011 (gmt 0)

WebmasterWorld Administrator httpwebwitch is a WebmasterWorld Top Contributor of All Time 10+ Year Member



use an incrementing variable, and do something when it's equal to 1. The first pass through, it will == 0, the second time it will == 1, and from then on it won't == 1.

$i = 0; // set it to zero
while($row = mysql_fetch_array($result)){

if ($i==1){ // do something if it's equal to 1
echo "-- ADD --";
}
echo $row['result'];

$i++; // increment the counter
}
4:54 pm on Nov 17, 2011 (gmt 0)

5+ Year Member



Thanks httpwebwitch,

It works exactly as I wanted, I just have a question, why if we're echoing "-- ADD --"; before echoing $row['result']; the add still appears after echoing $row['result'];?

Don't get me wrong, that's exactly how I want it to behave, I just want to understand why.
5:17 pm on Nov 17, 2011 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



<misread the q> it shouldn't. Like said, first time through it's zero:

echo "<p>$i</p>";
if ($i==1){ // do something if it's equal to 1
echo "<p>-- ADD --</p>";
}
echo $row['result'];

Should give you

0
[result row 1]
1
-- ADD --
[result row2]
3
[result row3]
4
[result row4]
.......
5:47 pm on Nov 17, 2011 (gmt 0)

5+ Year Member



Ahh, so I forgot to think as a computer, first result is actually number 0...
 

Featured Threads

Hot Threads This Week

Hot Threads This Month