清空DATETIME值存储为EA 00:00:00而不是MySQL中的NULL

时间:2016-01-20 16:46:43

标签: php mysql datetime null

我有可选的日期和时间表单字段,它们组合在一起形成一个DATETIME - 友好字符串,然后发送到MySQL数据库。相关的MySQL列数据类型为DATETIME,默认值为NULL。当日期和时间字段完成时,它会正确保存;但是,当这些可选表单字段为空时,日期时间将存储为0000-00-00 00:00:00而不是NULL。它需要存储为NULL,我不知道它为什么不存在。这是我的代码:

$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')";

表单日期采用DD / MM / YYYY格式,因此implode(...array_reverse(...))转换为MySQL友好DATETIME YYYY-MM-DD格式。将':00'附加到时间值同样适用,因为表单字段jQuery timepicker仅设置为hh:mm - 不需要秒。

也许它与SQL语句中$Date_Time_Query_Received周围的引号有关;但是如果没有它们,查询就会失败。

1 个答案:

答案 0 :(得分:4)

因此,如果你查看你的查询,你试图将日期列设置为字符串' ',这显然不会让MySQL开心。这是一个非常宽容的数据库,defaults to its fallback for a DATETIME column0000-00-00 00:00:00

那么,如何从PHP向数据库传递空值?尝试使用如下的预处理语句:

if (empty($_POST['Date_Query_Received']) || empty($_POST['Time_Query_Received'])) {
    $Date_Time_Query_Received = NULL;
} else {
    $Date_Query_Received2 = implode("-", array_reverse(explode("/", $_POST['Date_Query_Received'])));
    $Time_Query_Received2 = "$_POST[Time_Query_Received]:00";
    $Date_Time_Query_Received = "$Date_Query_Received2 $Time_Query_Received2";
}
$stmt = $conn->prepare("INSERT INTO log (Date_Time_Query_Received) VALUES (?)");
$stmt->bind_param("s", $Date_Time_Query_Received);
$stmt->execute();

除了使传递空值更容易之外,您还可以比使用mysqli_real_escape_string()更有效地保护自己免受SQL注入攻击。