How to store NULL values in datetime fields in MySQL?

后端 未结 8 529
再見小時候
再見小時候 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:30

    Specifically relating to the error you're getting, you can't do something like this in PHP for a nullable field in MySQL:

    $sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . null . ')';
    

    Because null in PHP will equate to an empty string which is not the same as a NULL value in MysQL. Instead you want to do this:

    $sql = 'INSERT INTO table (col1, col2) VALUES(' . $col1 . ', ' . (is_null($col2) ? 'NULL' : $col2). ')';
    

    Of course you don't have to use is_null but I figure that it demonstrates the point a little better. Probably safer to use empty() or something like that. And if $col2 happens to be a string which you would enclose in double quotes in the query, don't forget not to include those around the 'NULL' string, otherwise it wont work.

    Hope that helps!

提交回复
热议问题