Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert null into Datetime field

Tags:

php

mysql

I have a DATETIME column(Default is NULL) in MySQL and trying to insert Empty or NULL value. But I am getting "Incorrect datetime value: '' " error message. If I insert 'NULL' then I am getting "Incorrect datetime value: 'NULL'" error message. How can I insert a blank or NULL value in this column? Thank you for any suggestions.

Here is the code.

        if (empty($_POST["date_field"]))
        {      
          $Date1 = 'NULL';
        }
        else
        {
           $Date1 = strtotime($_POST["date_field"]);
           $Date1 = date("Y-m-d H:i:s", $Date1);
        }

   INSERT INTO Table1(date_field) VALUES('" .$Date1. "');
like image 644
nav100 Avatar asked Jan 18 '23 13:01

nav100


1 Answers

Your problem here is that you're inserting 'NULL' surrounded in quotes, which makes it a string. Instead you need the bare NULL

 if (empty($_POST["date_field"]))
 {      
   $Date1 = NULL;
 }
 else
 {
   $Date1 = strtotime($_POST["date_field"]);
   $Date1 = date("Y-m-d H:i:s", $Date1);
 }

// Surround it in quotes if it isn't NULL.
if ($Date1 === NULL) {
  // Make a string NULL with no extra quotes
  $Date1 = 'NULL';
}
// For non-null values, surround the existing value in quotes...
else $Date1 = "'$Date1'";

// Later, inside your query don't use any additional quotes since you've already quoted it...
INSERT INTO Table1(date_field) VALUES($Date1);
like image 149
Michael Berkowski Avatar answered Jan 20 '23 02:01

Michael Berkowski