简体   繁体   English

检测PHP mysqli中的空列值

[英]Detect null column value in PHP mysqli

I have a php project that uses mysqli to query a database. 我有一个使用mysqli查询数据库的php项目。 Some of the columns in this database can be null. 此数据库中的某些列可以为null。 I have code that looks something like this: 我的代码看起来像这样:

$query = "...";
$result = $DB->query($query);
$row = $result->fetch_assoc();
$column = $row['mycolumn'];

If mycolumn is null, the value of $column appears to be the string, "NULL" (NOT the null value, but actually the string containing the word "NULL"). 如果mycolumn为null,则$column的值显示为字符串"NULL" (不是空值,但实际上是包含单词“NULL”的字符串)。 So what happens if I have columns which actually have the string "NULL" in them? 那么如果我的列实际上有字符串"NULL"发生什么呢? How can I differentiate? 我该如何区分?

Thanks! 谢谢! Josh 玩笑

EDIT: Upon closer inspection, it appears that the string is actually a 5-characters string. 编辑:仔细检查后,发现该字符串实际上是5个字符的字符串。 The first 4 characters are "NULL" , but the last character is 0x0d, the carriage return. 前四个字符为"NULL" ,但最后一个字符为0x0d,回车。 This makes it a lot easier to detect, although I'm still curious if there's a less hack-y way than just doing string comparison. 这使得它更容易被发现,尽管我仍然很好奇,如果没有比只进行字符串比较更少的hack-y方式。

Use an if condition to check with === 使用if条件检查===

if($row['mycolumn'] === null) {
   echo 'Real Null';
} elseif($row['mycolumn'] == '') {
   echo 'Blank';
}

You are looking wrong way. 你看错了路。 Instead of trying to detect wrong NULL value you have to find out why it is wrong and correct it. 而不是试图检测错误的 NULL值,你必须找出它为什么是错误的并纠正它。

Neither Mysql nor mysqli would return a literal string 'NULL' for a null value. Mysql和mysqli都不会为null值返回文字字符串'NULL'。

So, you need to find your own code which converts NULL value to "NULL\\n" string either at writing or reading. 因此,您需要找到自己的代码,以便在写入或读取时将NULL值转换为“ NULL \\ n”字符串。 Are you using raw mysqli as $DB or it's a sort of abstraction class? 您使用原始mysqli作为$ DB还是一种抽象类? If so - I'd say problem is there. 如果是这样-我会说问题出在那儿。

After that you can easily read NULL value with strict comparison === as suggested in other answers (though I am not sure about libmysql installations). 之后,你可以很容易地读取NULL值,严格比较===如其他答案中所建议的那样(虽然我不确定libmysql的安装)。

seems the column have the data type as string. 似乎该列的数据类型为字符串。

If it is string, 如果是字符串,

we can check by following 我们可以通过以下检查

if($row['mycolumn'] == '' || is_null($row['mycolumn']))
{
    echo "Coulmn is NULL value";
}
else if($row['mycolumn'] == "NULL")
{
    echo "Coulmn is NULL value as string";
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM