How to store NULL values in datetime fields in MySQL?

后端 未结 8 535
再見小時候
再見小時候 2020-11-29 05:44

I have a \"bill_date\" field that I want to be blank (NULL) until it\'s been billed, at which point the date will be entered.

I see that MySQL does not like NULL val

8条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-29 06:17

    MySQL does allow NULL values for datetime fields. I just tested it:

    mysql> create table datetimetest (testcolumn datetime null default null);
    Query OK, 0 rows affected (0.10 sec)
    
    mysql> insert into datetimetest (testcolumn) values (null);
    Query OK, 1 row affected (0.00 sec)
    
    mysql> select * from datetimetest;
    +------------+
    | testcolumn |
    +------------+
    | NULL       | 
    +------------+
    1 row in set (0.00 sec)
    

    I'm using this version:

    mysql> select version();
    +-----------+
    | version() |
    +-----------+
    | 5.0.45    | 
    +-----------+
    1 row in set (0.03 sec)
    

    EDIT #1: I see in your edit that the error message you are getting in PHP indicates that you are passing an empty string (i.e. ''), not null. An empty string is different than null and is not a valid datetime value which is why you are getting that error message. You must pass the special sql keyword null if that's what you mean. Also, don't put any quotes around the word null. See my insert statement above for an example of how to insert null.

    EDIT #2: Are you using PDO? If so, when you bind your null param, make sure to use the [PDO::PARAM_NULL][1] type when binding a null. See the answer to this stackoverflow question on how to properly insert null using PDO.

提交回复
热议问题