在 PHP 中,NULL 和将字符串设置为等于 2 个单引号有什么区别

2022-01-06 00:00:00 null php

当我想要空白值时,我曾经设置过这样的东西.

I used to set things like this when I wanted blank values.

$blankVar = '';

几个月后,我觉得这看起来更好,意图更清晰.

Then after some months, I decided this looked better and had a clearer intent.

$blankVar = null;

这有一段时间没有打嗝,但最近使用 PDO 准备好的语句我遇到了问题.将值绑定到 null 会使查询失败,而将其绑定到 '' 则不会.我需要把它绑定到null,这样如果满足条件,它就会插入空白数据.

This worked without hiccup for a while, but recently with a PDO prepared statements I ran into a problem. Binding a value to null made the query fail, whilst binding it to '' did not. I needed to bind it to null, so that if a condition was met, it would insert blank data.

两者有什么区别?我仍然认为等于 null(或至少是一个常数)看起来更好,所以我应该这样做吗?

What are the differences between the 2? I still think equaling null (or at least a constant) looks better, so should I do this?

define('EMPTY', '');

推荐答案

Null 只是 PHP 中的另一种数据类型,它只有一个值 (null). 由于 PHP 是一种松散类型的语言,它可能会混淆它处理不同值的方式.

Null is just another datatype in PHP, which has only one value (null). Since PHP is a loosly typed language, it can be confusing how it handles different values.

"", 0, "0", False, array(), Null 在 PHP 中都被认为是 False.

"", 0, "0", False, array(), Null are all considered False in PHP.

然而,Null 是一种不同的动物.与使用 Null 的主要不兼容之处在于您无法判断它是否为 isset().

Null, however, is a different kind of animal. The main incompatibility with using Null is that you cannot tell if it isset().

$x = false;
isset($x)  ->  true
echo $x    ->  ""

$y = null;
isset($y)  ->  false
echo $y    ->  ""

//$z is not set
isset($z)  ->  false
echo $z    ->  E_NOTICE

因此 null 很奇怪,因为它不遵循 PHP 中的正常变量规则(至少是一些).在大多数情况下,没问题.

So null is odd in the sense that it doesn't follow normal variable rules in PHP (at least some). In most cases, it is fine.

说到数据库列,PHP 的 NULL 没有位置. 你看,SQL 是一种基于字符串的语言.SQL 的 NULL 必须由不带引号的 NULL 表示.

When it comes to database columns, PHP's NULL has no place there. You see, SQL is a string based language. SQL's NULL must be represented by NULL with no quotes.

因此,如果您想要一个 EMPTY 字段,请将其设置为"

So if you want an EMPTY field, set it to ""

INSERT INTO foo SET bar = ""

但是如果你想要一个 NULL 字段,请将其设置为 NULL

But if you want a NULL field, set it to NULL

INSERT INTO foo SET bar = NULL

大不同.

但是如果您尝试直接插入 PHP NULL,它会在查询中添加零个字符(这会导致空白或语法错误,具体取决于您是否引用了它).

But if you try to insert the PHP NULL directly, it will add zero characters to the query, (which leaves you with a blank or syntax error, depending on if you quoted it).

相关文章