I have optional date and time form fields which are combined to form a DATETIME
-friendly string, which is then sent to the MySQL database. The relevant MySQL column data type is DATETIME
, with a default value of NULL
. It saves correctly when the date and time fields are completed; however when these optional form fields are empty, the datetime is stored as 0000-00-00 00:00:00
instead of NULL
. It needs to be stored as NULL
and I have no idea why it isn't. Here's my code:
$Date_Query_Received1 = mysqli_real_escape_string($conn, $_POST['Date_Query_Received']);
$Date_Query_Received2 = implode("-", array_reverse(explode("/", $Date_Query_Received1)));
$Time_Query_Received1 = mysqli_real_escape_string($conn, $_POST['Time_Query_Received']);
$Time_Query_Received2 = $Time_Query_Received1.':00';
if (empty($_POST['Date_Query_Received']) || empty($_POST['Time_Query_Received'])) {
$Date_Query_Received = NULL;
$Time_Query_Received = NULL;
} else {
$Date_Query_Received = $Date_Query_Received2;
$Time_Query_Received = $Time_Query_Received2
}
$Date_Time_Query_Received = $Date_Query_Received.' '.$Time_Query_Received;
mysqli_query($conn, "INSERT INTO log (Date_Time_Query_Received) VALUES ('$Date_Time_Query_Received')";
The form dates are in DD/MM/YYYY format, hence implode(...array_reverse(...))
to convert to MySQL-friendly DATETIME
YYYY-MM-DD format. The same applies with appending ':00' to the time value, as the form field jQuery timepicker is set up for hh:mm only - seconds are not required.
Perhaps it has something to do with the quotes around $Date_Time_Query_Received
in the SQL statement; however the query fails without them.