【问题标题】:How to check if MySQL returns null/empty?如何检查 MySQL 是否返回 null/empty?
【发布时间】:2010-12-14 04:28:11
【问题描述】:

在 DB 中,我有一个表,其中包含一个名为 fk_ownerID 的字段。默认情况下,当我添加新表行时,fk_ownerID 为空。在 Toad for MySQL 中,这显示为 {null}。如果fk_ownerID 被赋予了一个值,而我稍后删除了这个值,我就设置了fk_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') )

但我很确定这些测试中只有一项是必要的。

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

【问题讨论】:

    标签: php mysql


    【解决方案1】:

    你可以使用 is_null() 函数。

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

    mdufour 在 gmail dot com 2008 年 8 月 20 日 04:31 测试 mySQL 查询返回的 NULL 字段/列。

    假设您想检查当 mySQL 查询返回的 > 为空时,表“bar”的给定行中的字段/列“foo”是否为空。 您只需使用“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"];
    […]
    

    【讨论】:

      【解决方案2】:

      使用 empty() 和/或 is_null()

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

      Empty 将实现您当前的使用,如果您想区分空字段和空字段,is_null 只会使更多控制成为可能。

      【讨论】:

      • 所以我必须使用 empty() AND is_null()?
      • ok.... empty() 应该这样做 :) --> 如果 var 具有非空且非零值,则返回 FALSE。以下内容被认为是空的: "" (一个空字符串) 0 (0 作为一个整数) "0" (0 作为一个字符串) NULL FALSE array() (一个空数组) var $var; (声明的变量,但在类中没有值)
      • 我认为is_null() 更安全,因为如果变量的值为零,它仍被视为empty()
      【解决方案3】:

      此外,当您处理可能表示 null 或 0 或返回某种形式的 false 或 null 的数字时,不要忘记 === 运算符,这不是您要查找的。​​p>

      【讨论】:

      • 这没有回答问题。
      • 我同意,应该留下评论。
      【解决方案4】:
      select FOUND_ROWS();
      

      将返回没有。选择查询选择的记录数。

      【讨论】:

        【解决方案5】:

        假设

        $row=mysql_fetch_row($rc)
        and if you want to check if row[8] is null then do
        $field=$row[8];
           if($field)
        echo "";
        else
         echo ""; 
        

        【讨论】:

          【解决方案6】:
          if ( (strlen($ownerID) == 0) || ($ownerID == '0') || (empty($ownerID )) )
          

          如果 $ownerIDNULL 它将由 empty() 测试触发

          https://www.php.net/empty

          【讨论】:

            【解决方案7】:

            如果你的mysql数据库中的数据类型是自增主键,那么你不能使用is_null()你必须使用empty()或者在代码中,它会是if (empty($id)) {

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2020-04-15
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-04-19
              • 2023-03-21
              • 2017-12-24
              相关资源
              最近更新 更多