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);
3
Answers
You can resolve this with some slight changes to your code (take note of single and double quotes):
This way if you’re setting a NULL value in timestamp the query would look something like this:
But if you’re putting a value in there it would look like this:
Important to note there are no quotes around the NULL when setting the value, but there are around the date.
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 value0000-00-00 00:00:00
will be converted to NULL:Or you can simply:
And use PHP to pass a variable containing string or
null
.