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.
Any PHP developer there?
I normally use
foreach / else to display tables.
$q = mysql_query(‘SELECT * FROM tbl’);
$n = 0;
while($r = mysql_fetch_assoc($q))
{
// do something
++$n
}
if(0 == $n)
{
// no rows found
}
Pingback: Richard K Miller dot coooooooooom » PHP 5 and Beyond
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”;
}
while(!(connection_aborted() || connection_status() == 1) && $bytes_sent content_length)
{
//this sends data
if(connection_aborted() || connection_status() == 0) {log_write(“Seems the client aborted the file download”); break;}
}
Request #26411 – while {} else {}
There is also a feature request for the corresponding foreach statement:
Request #46240 – Build in foreach else support
Please visit and vote!
No registration or additional details required to vote.
You can subscribe or comment in the ‘Add Comment’ tab by just adding your mail, no registration needed.
$hasresult=false;
while($row=mysql_fetch_assoc($mysqlResult)){
}
A solution (simpler than taaniel’s one) is to put a flag :
$hasresult=false;
while($row=mysql_fetch_assoc($mysqlResult)){
[do whatever you want]
$hasresult=true;
}
if(!$hasresult){
[do whatever you want]
}