Page 1 of 1
If statement
Posted: Wed Mar 30, 2005 5:26 pm
by Jim_Bo
Hi,
How do you acheive an if statment where a sql query finds no results echo bla bla .. else if there is a result found .. display it
Code: Select all
$sql = "SELECT * FROM table WHERE bla = 'no' ORDER BY date ASC LIMIT 1";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) { ..
?
Thanks
Posted: Wed Mar 30, 2005 5:32 pm
by Burrito
what I do if I think I'm going to have multiple rows that I want to loop over is just check if it returned any rows with mysql_num_rows(). If that isn't 0 then do your while loop.
if you are just going to return one row you can use if instead of while
Code: Select all
if($rows = mysql_fetch_assoc($result)){
echo "stuff";
}else{
echo "no rows returned";
}
Burr
Posted: Wed Mar 30, 2005 6:53 pm
by Jim_Bo
Hi,
Is it ment to be something like:
Code: Select all
$sql = "SELECT * FROM table WHERE bla = 'no' ORDER BY date ASC LIMIT 1";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
$blabla = $row['blabla'];
if($rows = mysql_fetch_assoc($result)){
echo "$blabla";
}else{
echo "No records found";
}
}
It stills echos no results ..
Thanks ..
Posted: Wed Mar 30, 2005 7:04 pm
by John Cartwright
Code: Select all
$sql = "SELECT * FROM table WHERE bla = 'no' ORDER BY date ASC LIMIT 1";
$result = mysql_query($sql);
if (mysql_num_rows($result) > 0)
{
while ($row = mysql_fetch_array($result))
{
$blabla = $row['blabla'];
}
}
else
{
echo 'No Records found';
}
}
Posted: Wed Mar 30, 2005 7:07 pm
by thegreatone2176
you have a while then a for and you dont concatanate the variable and you have the variable in quotes so its not going to eval it. and its easier to use mysql_num_rows to check than an else
try this
Code: Select all
$blabla = ""; // I dont use php5 but if you are i think you need to initalize
// the var before concatnating it
$total = mysql_num_rows($result);
if ($total == 0) { echo 'no results found'; die; }
while ($row = mysql_fetch_array($result)){
$blabla .= $row['blabla']; // note the dot
echo $blabla;
that should make your code work and the variable echo
Posted: Wed Mar 30, 2005 7:29 pm
by John Cartwright
Firstly, the variable will be evaled in double quotes.
Secondonly, no need for concatenation operator..
Thirdly,
and its easier to use mysql_num_rows to check than an else
What else? And I am using mysql_num_rows..
Quadly,
In your snipplet you use exit() if no rows are returned. Sometimes this should be done if you are always expecting rows, but what if you are not?
Posted: Wed Mar 30, 2005 7:53 pm
by thegreatone2176
ok well I didnt even respond to your post. I responded to jim bo's your post wasnt even there at the time i posted.
Posted: Wed Mar 30, 2005 9:27 pm
by Jim_Bo
Hi,
Thanks for all the help guys ..
Phenom .. your code worked great ..
Thanks