February 19, 2006...2:25 am
PHP needs a while-else statement
I think PHP ought to have a while-else statement. There is, of course, a while statement and an if-else statement, but a while() else statement would be perfect for returning a bunch of rows from a MySQL database:
<?php
$q = mysql_query(“SELECT name FROM people WHERE age >= 21″);
while ($person = mysql_fetch_assoc($q))
{
echo “$person[name] is at least 21 years old.”;
}
else
{
echo “No one 21 or older was found in the database!”;
}
?>
This hypothetical code queries the database for everyone age 21 or older, looping through all the results. If no results were found, it very conveniently says so. Because there is no while-else statement, the programmer has to nest the the while() loop inside an if() statement. A while-else statement would be much cleaner.
If you want to be notified the next time I write something, sign up for email alerts or subscribe to the RSS feed. Thanks for reading.
7 Comments
February 20, 2006 at 2:57 pm
February 20, 2006 at 3:42 pm
Any PHP developer there?
February 20, 2006 at 6:00 pm
I normally use
foreach / else to display tables.
February 21, 2006 at 2:12 am
$q = mysql_query(’SELECT * FROM tbl’);
$n = 0;
while($r = mysql_fetch_assoc($q))
{
// do something
++$n
}
if(0 == $n)
{
// no rows found
}
August 16, 2006 at 11:34 pm
August 21, 2006 at 2:19 pm
July 16, 2008 at 2:04 pm
if (list($a,$b) = mysql_fetch_row($result)) {
do {
process($a,$b);
} while (list($a,$b) = mysql_fetch_row($result));
} else {
print “No results returned”;
}
Leave a Reply