Welcome to WebmasterWorld Guest from 54.159.214.27

Forum Moderators: coopster & jatar k

Can special conditions be made in WHILE statement if output is first?

Similar to FOR statement if I had if($i==1){...}

   
3:35 pm on Jan 20, 2007 (gmt 0)

5+ Year Member



I'm using PHP's while function to output data from a MySQL table:

$result=mysql_query("SELECT * FROM x WHERE parameter="y" ORDER BY z");
while($row=mysql_fetch_array($result))
echo "<input type=\"radio\" name=\"a\" value=\"".$row["b"]."\" checked=\"checked\" />";

What I'm trying to do is to get the first one that outputs to be checked, and the rest not to be checked. As written above, all will have the checked output which is invalid.

If this were a for statement, something like i=1;i<count;i++, then I could have a statement below that has a special condition if i==1.

Is there anything I can do like this for the while statement?

Might I be able to use the for statement and not mess up the output of the MySQL data?

Thanks

4:00 pm on Jan 20, 2007 (gmt 0)

WebmasterWorld Senior Member eelixduppy is a WebmasterWorld Top Contributor of All Time 5+ Year Member



You could do something like this:

while($row = mysql_fetch_array($result)) {
if($row['field']!= "foobar") {
[url=http://us2.php.net/break]break[/url];
}
//continue with loop
}

Good luck! :)

[edited by: eelixduppy at 4:30 pm (utc) on Jan. 20, 2007]

4:28 pm on Jan 20, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



It can be a for statement, as long as you still check for the condition where MySQL has no more data. Or even an if, if you only one the first record. There's nothing special about while.

Or, just implement your own counter in the while loop, to make it act like a for.

6:32 pm on Jan 20, 2007 (gmt 0)

WebmasterWorld Senior Member 5+ Year Member



Or you can do the first one separately:
$result=mysql_query("SELECT * FROM x WHERE parameter="y" ORDER BY z");
$row=mysql_fetch_array($result);
echo "<input type=\"radio\" name=\"a\" value=\"".$row["b"]."\" checked=\"checked\" />";
while($row=mysql_fetch_array($result))
echo "<input type=\"radio\" name=\"a\" value=\"".$row["b"]."\" />";
1:28 pm on Jan 22, 2007 (gmt 0)

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



And yet another option is to build the list into a variable rather than echo it to the browser on each iteration. If the list is empty, you know you are on the first checkbox option and you can set it to be checked. Otherwise, set the checked option to nothing. Then concatenate [php.net] the output into your initialized variable, something along these lines ...
$out = ''; // initialize 
while (processing rows) {
$checked = ($out) ? '' : ' checked="checked"';
$out .= '<input type="radio" name="a" value="' . htmlentities($row['b']) . "$checked />";
}
 

Featured Threads

My Threads

Hot Threads This Week

Hot Threads This Month