views:

1199

answers:

3

Hello, here is the description variable I am echoing from my table:

$description = mysql_result($result,$i,"description");

sometimes the $i'th record is empty and doesn't have any data in it/no description.

What I want to do is echo "No description available" for records that are empty

if (isset($description)){ echo "No description available";}
else{ echo $desctipion;}

My attempt doesn't work though as it then echoes No description available for every record even those which aren't empty.

What is the answer?

A: 

Use the mysql_affected_rows function:

$qtd = mysql_affected_rows($result);

Cesar
That won't make a difference if the column contains a NULL value.
Matt Huggins
Sorry, I read wrong the question. Your answer is correctly. +1 For you :)
Cesar
+4  A: 

isset($description) will result true because $description is still set, even though its value is 'empty'. What you need to use is empty.

if (empty($description)) {
    echo "No description available";
} else {
    echo $description;
}
Matt Huggins
Works perfect, thanks a lot.
David Willis
A: 

It depends on what you mean.

mysql_result returns FALSE on failure, which would happen if you specified an invalid (row,field). To check for this you'd want to do use the identicality operator '===', which checks both value and type. The equality operator ==, the empty() function, and the conditional evaluation of an if statement all check the value but not the type.

This means that using one of those methods there's no difference between various values that all equate to Boolean FALSE, like empty strings, empty arrays, the string '0', and the value NULL.

So if you want to be really thorough about it you could do something like the following:

if ($description === FALSE) {
  throw new Exception("The row $i was out of range in query $query.");
} else if ($description === NULL) {
  // assuming that the description field has a default value of NULL
  // * this one I'm not sure about.. the documentation for mysql_result claims
  //   that it returns a string, so this may never happen.
  //   It's left as an exercise for the reader.
  throw new Exception("Uninitialized value in result row $i of db query $query");
} else if ($description === '') {
  echo "No description available";
} else {
  echo $description;
}

Since empty() returns true under a similar set of conditions to an equality (==) with FALSE, this more strict in your type checking would be especially important in cases where the result might actually be "0".

Apparently I'm not allowed to post more than one hyperlink, so I wasn't able to link to the documentation for comparison operators ("http://php.net/manual/en/language.operators.comparison.php") or the empty function ("http://php.net/empty"). Fortunately their security is relatively lax. Mwuh Hah!

intuited