0

how to insert null date mysql real scape string

if (empty($DATE_PURCHASED)) {
    $DATE_PURCHASED = NULL;
} 

//sql query
$queryString = sprintf("INSERT INTO IT_ASSET_RADIO (BRAND_NAME, SERIAL_NO, DATE_PURCHASED, LICENSE_NO) 
    values ('%s','%s', '%s', '%s')",
    mysql_real_escape_string($BRAND_NAME),
    mysql_real_escape_string($SERIAL_NO),
    mysql_real_escape_string($DATE_PURCHASED),
    mysql_real_escape_string($LICENSE_NO));

$query = mysql_query($queryString ) or die("Insert failed: " . mysql_error());

I got an error of this query invalid date in DATE_PURCHASED if value is null

json
  • 37
  • 5

3 Answers3

1
$date=mysql_real_escape_string($DATE_PURCHASED); 
if(trim($date)==''){ $date=NULL;}

use $date in your query.

And also

set DATE_PURCHASED column in table default NULL

safin chacko
  • 1,345
  • 1
  • 11
  • 18
  • That won't work in strict mode, not sure about others. If you specify an empty string, it will try to insert an empty string, not a NULL value. Defaults are useful for when the column is excluded from the insert statement. – Devon Bessemer Feb 23 '16 at 05:01
  • I already set the DATE_PURCHASED into null but nothing works. – json Feb 23 '16 at 05:03
0

Try to pass the date string in the format like 'YYYY-MM-DD HH:MM:SS', do it like below:

..........mysql_real_escape_string(date('Y-m-d H:i:s', strtotime($DATE_PURCHASED))).....
Kausha Mehta
  • 2,828
  • 2
  • 20
  • 31
  • Woh! it doesnt return null.. XD – json Feb 23 '16 at 05:22
  • @json If this answer is useful to you then please accept it and up vote it, so other knows that, you got the solution. None other waste their time to find the solution. – Kausha Mehta Feb 23 '16 at 05:25
  • @json It doesn't return null, but you got the diff error. You just have to check it before passing to the mysql query and if the variable is blank then set the variable blank and if they have any value then you have to pass it to DB with correct format. – Kausha Mehta Feb 23 '16 at 05:28
0
if (empty($DATE_PURCHASED)) {      
      $DATE_PURCHASED = NULL;
    } else {
       $DATE_PURCHASED = $data->DATE_PURCHASED;
    }
    // Surround it in quotes if it isn't NULL.
    if ($DATE_PURCHASED === NULL) {
      // Make a string NULL with no extra quotes
      $DATE_PURCHASED = 'NULL';
    }
    // For non-null values, surround the existing value in quotes...
    else $DATE_PURCHASED = "'$DATE_PURCHASED'";

$queryString = sprintf("INSERT INTO IT_ASSET_RADIO (BRAND_NAME, SERIAL_NO, DATE_PURCHASED, LICENSE_NO) 
    values ('%s','%s', $DATE_PURCHASED , '%s')",
    mysql_real_escape_string($BRAND_NAME),
    mysql_real_escape_string($SERIAL_NO),
    mysql_real_escape_string($LICENSE_NO));

$query = mysql_query($queryString ) or die("Insert failed: " . mysql_error());
json
  • 37
  • 5