Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL, how to insert null dates

I am having trouble inserting null values into date fields into a MySQL table.

Here is the insert query:

$query = 'INSERT INTO table (column_s1, column_s2, column_d1, column_d2)
VALUES ("'.$string1.'", "'.$string2.'", '.$date1.', '.$date2.')';

Columns s1 and s2 take string values and d1 and d2 take dates. When I run this query with only the string fields, there is no problem.

The date values can be either set or null, so I have not included the quotation marks in the query, but have instead added them to the variable earlier on. This is the php code I am using to set the date values:

if (empty($date1)){
    $date1 = NULL;
}
else{
    $date1part = explode("/",$date1);
    $date1 = '"'.$date1part[2].'/'.$date1part[1].'/'.$date1part[0].'"';
}

When the date values are all set, the record is inserted correctly. However, when either of the dates is null, nothing is inserted.

Why can't I just insert null values into MySQL like this?

like image 593
ajor Avatar asked Jul 22 '13 09:07

ajor


People also ask

Can we insert NULL in date in MySQL?

It's because MySQL is actually trying to insert the literal string 'NULL' into a DATE column, not the actual value NULL . Your choices are: Global search for |NULL| in your file and replace with ||

How do you insert a date NULL?

"NULL" can be specified as a value in the Date field to get an empty/blank by using INSERT statement. Example: CREATE table test1 (col1 date); INSERT into test1 values (NULL);

How do you insert a date in MySQL?

MySQL comes with the following data types for storing a date or a date/time value in the database: DATE - format YYYY-MM-DD. DATETIME - format: YYYY-MM-DD HH:MI:SS. TIMESTAMP - format: YYYY-MM-DD HH:MI:SS.


1 Answers

Try this:

$query = "INSERT INTO table (column_s1, column_s2, column_d1, column_d2) 
          VALUES ('$string1', '$string2', " . ($date1==NULL ? "NULL" : "'$date1'") . ", " . ($date2==NULL ? "NULL" : "'$date2'") . ");";

so for example if you put this into query:

$string1 = "s1";
$string2 = "s2";
$date1 = NULL;
$date2 = NULL;

result should be:

INSERT INTO table (column_s1, column_s2, column_d1, column_d2) VALUES ('s1', 's2', NULL, NULL);
like image 185
Wh1T3h4Ck5 Avatar answered Sep 19 '22 13:09

Wh1T3h4Ck5