如何检查MySQL是否返回空/空?

2022-08-30 14:35:04

在 DB 中,我有一个表,其中包含一个名为 .默认情况下,当我添加新的表行时,它是空的。在 Toad for MySQL 中,这显示为 .如果给定一个值,并且我稍后删除了此值,则设置 .fk_ownerIDfk_ownerID{null}fk_ownerIDfk_ownerID = ""

现在,我有以下代码:

$result = $dal->getRowByValue('tableName','id', $_POST['myID']);

// Check to see if any rows where returned
if (mysql_num_rows($result) > 0)
{
  while ($row = mysql_fetch_array($result))
  {
    $ownerID = $row["fk_ownerID"];    
  }
}

现在变量$ownerID应该有一个数字,或者没有。但我不确定如何检查这一点。目前我正在这样做:

if ( (strlen($ownerID) == 0) || ($ownerID == '0') || ($ownerID == 'null') )

但我非常确定这些测试中只有一个是必要的。

检查行字段是否为空或为空的最佳方法是什么?


答案 1

使用空() 和/或 is_null()

http://www.php.net/empty http://www.php.net/is_null

单独为空将实现您当前的使用,is_null只是想区分空字段和空字段,则可以进行更多控制。


答案 2

您可以使用 is_null() 函数。

http://php.net/manual/en/function.is-null.php : 在评论中 :

mdufour at gmail dot com 20-Aug-2008 04:31 测试 mySQL 查询返回的 NULL 字段/列。

假设您想检查表“bar”的给定行中的字段/列“foo”,当mySQL查询返回的>为空时。您只需使用“is_null()”函数:

[connect…]
$qResult=mysql_query("Select foo from bar;");
while ($qValues=mysql_fetch_assoc($qResult))
     if (is_null($qValues["foo"]))
         echo "No foo data!";
     else
         echo "Foo data=".$qValues["foo"];
[…]

推荐