Forum Moderators: coopster

Message Too Old, No Replies

using isset is null or empty or something else?

         

surrealillusions

11:57 am on May 13, 2008 (gmt 0)

10+ Year Member



Hi,

I'm trying to do something that is probably really easy.

What im doing is extracting something from a database, but if nothing is there to extract, then it echos a message "nothing in the database".

I've tried variations on this theme, including isset, is_null, swapping the statement order around etc etc...I've got it showing both the data, and the no hegdehogs, but not at the right times, or nothing at all...

$data = mysql_query ("SELECT * FROM database WHERE animals='hedgehogs' ORDER BY id DESC")
or die (mysql_error());

while ($info = mysql_fetch_array( $data ))

if (empty($data)) {
echo "<p>No hedgehogs currently live here...</p>";
}
else
{
echo "<p>This is a: " .$info['animals'] . "</p>";
}

where am i going wrong?

thanks
:)

dreamcatcher

12:45 pm on May 13, 2008 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Try comparing by the amount of rows returned:

while ($info = mysql_fetch_array( $data ))

if (mysql_num_rows($data)==0) {
echo "<p>No hedgehogs currently live here...</p>";
}
else
{
echo "<p>This is a: " .$info['animals'] . "</p>";
}

dc

surrealillusions

2:00 pm on May 13, 2008 (gmt 0)

10+ Year Member



thanks..but doesn't appear to do what i need..

when theres nothing in the database, it echos nothing..but it does produce the stuff in the database when there is something.

d40sithui

2:29 pm on May 13, 2008 (gmt 0)

10+ Year Member



i think you need to check for the rows BEFORE your while loop.
so something like this

//if rows found
if(mysql_num_rows($data)){
while($info = mysql_fetch_array($data)){
//do stuff here
}
}
else{
echo "No data found.";
}

paulmadillo

3:27 pm on May 13, 2008 (gmt 0)

10+ Year Member



Forgive me if I'm wrong but I don't think you're quite getting what he's asking.

I think the problem is that sometimes a field is 'Null', sometimes it is 'empty' and sometimes it contains a blank string.

This is a problem I have quite often, especially with CMS based sites.

The way I usually go about it is to check for a few different eventualities such as:

if (empty($data) ¦¦ is_null($data) ¦¦ $data == '') {
echo "<p>No hedgehogs currently live here...</p>";
}
else
{
echo "<p>This is a: " .$info['animals'] . "</p>";
}

I don't know whether the things I'm checking for are one and the same but this solution usually works for me.