I’m using this code to update my datatime field to NULL, php version 7.3.7
if($_POST['value']=='0000-00-00 00:00:00'){ $timestamp=NULL; }else { $dateTime = $_POST['value']; $timestamp = date('Y-m-d H:i', strtotime($_POST['value'])); } $query="update forms set $_POST[limitInputField]='$timestamp' where formid='$_POST[formId]'"; $result=$dbCnn->query($query)or die($dbCnn->error);
it gives error when $timestamp is null:
Incorrect datetime value: ” for column farsifor_m.forms.enddate at row 1
But when I quote “NULL” and remove quotations around $timestamp in the query, if $timestamp is null it works properly but if $timestamp value is not null it gives error.
if($_POST['value']=='0000-00-00 00:00:00'){ $timestamp="NULL"; }else { $dateTime = $_POST['value']; $timestamp = date('Y-m-d H:i', strtotime($_POST['value'])); } $query="update forms set $_POST[limitInputField]=$timestamp where formid='$_POST[formId]'"; $result=$dbCnn->query($query)or die($dbCnn->error);
Advertisement
Answer
Learn to use prepared statements; and do not inject post variables to “build” the query. Having said that:
You can use NULLIF
for convenience. In the following example the specific value 0000-00-00 00:00:00
will be converted to NULL:
UPDATE forms SET col = NULLIF(:timestamp, '0000-00-00 00:00:00') WHERE formid = :formid
Or you can simply:
UPDATE forms SET col = :timestamp WHERE formid = :formid
And use PHP to pass a variable containing string or null
.