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);
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
.
You can resolve this with some slight changes to your code (take note of single and double quotes):
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]'";
This way if you're setting a NULL value in timestamp the query would look something like this:
update forms set limitInputField=NULL where formid='123'
But if you're putting a value in there it would look like this:
update forms set limitInputField='2019-09-03 17:08' where formid='123'
Important to note there are no quotes around the NULL when setting the value, but there are around the date.
$date = $_POST['Date']; //get date from form
$time = $_POST['Time']; //get time from form
if(strtotime($date.$time)==0){ // check if null or not
$AboutDate = "0000-00-00 00:00:00";
}else{
$AboutDate = date("Y-m-d H:i", strtotime($date.$time));
}
Then Update/Insert into SQL
UPDATE xxx(table) SET xxx(column) = NULLIF('$AboutDate','0000-00-00 00:00:00') WHERE xxxx = xxxxx
Let's go BABY
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.