2009-10-19 73 views
9

这里是描述可变我从我的表呼应:如何检查PhP中的mysql条目是否为空?

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

有时$第i个记录是空的,不具有任何数据/没有说明。

我想要做的是回声是空

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

我尝试不工作,虽然,因为它呼应然后对每条记录:无说明即使是那些不是活得记录“没有可用的描述” t空了。

答案是?

回答

25

isset($description)将导致真实的,因为$描述仍设置,即使它的值是“空”。你需要使用的是empty

if (empty($description)) { 
    echo "No description available"; 
} else { 
    echo $description; 
} 
+0

完美的作品,非常感谢。 – 2009-10-19 23:08:38

+0

你永远不需要使用空! – dynamic 2012-01-28 15:59:02

+2

@ yes123:请您详细说明一下吗?你不需要每个帐户都需要它,但为什么不使用它? – Sk8erPeter 2012-06-19 09:32:07

0

使用mysql_affected_rows功能:

$qtd = mysql_affected_rows($result); 
+1

如果列中包含NULL值,那么这不会产生影响。 – 2009-10-19 23:07:18

+0

对不起,我看错了这个问题。你的回答是正确的。 +1对你:) – Cesar 2009-10-19 23:12:04

2

这取决于你的意思。

mysql_result返回FALSE失败,如果您指定了无效(行,字段),则会发生这种情况。要检查这一点,你想要使用同一性运算符===,它会检查值和类型。等号运算符==empty()函数以及if语句的条件求值都检查值,但不检查类型。

这意味着使用其中的一种方法,各个值之间没有区别,它们都等于Boolean FALSE,如空字符串,空数组,字符串'0'和值NULL

所以,如果你想成为真正彻底了解它,你可以这样做以下:在一系列类似的条件

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; 
} 

由于empty()回到true到平等(==)与FALSE,这更在结果可能实际上为"0"的情况下,严格的类型检查尤为重要。

显然我不允许发布多个超链接,所以我无法链接到比较运算符(“http://php.net/manual/en/language.operators.comparison.php”)或空函数(“http://php.net/empty”)的文档。幸运的是,他们的安全相对松懈。 Mwuh哈!