In PHP, what is the differences between NULL and setting a string to equal 2 single quotes

后端 未结 5 1328
情歌与酒
情歌与酒 2020-11-30 05:06

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

5条回答
  •  时光取名叫无心
    2020-11-30 05:09

    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 are all considered False in PHP.

    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
    

    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.

    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.

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

    INSERT INTO foo SET bar = ""
    

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

    INSERT INTO foo SET bar = NULL
    

    BIG DIFFERENCE.

    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).

提交回复
热议问题