在 MySQL 表中,我有一个名为 date 的字段,其类型称为时间戳,默认值为 CURRENT_TIMESTAMP
。但是,如果我在 MySQL 中将该字段留空,则会出现错误。当我尝试在其中插入类似 time()
的内容时,我收到的日期为 0000-00-00 00:00:00
。
<?php
$name = "";
$email = "";
$subject = "";
$comments = "";
$nameError = "";
$emailError = "";
$subjectError = "";
$x = 5;
function filterData($data)
{
$data = htmlspecialchars($data);
$data = stripslashes($data);
return $data;
}
$connection = mysql_connect('host', 'user', 'pass');
if (!$connection) {
die('Could not connect: ' . mysql_error());
}
$select_database = mysql_select_db("contact");
if (!$select_database) {
echo "could not select database " . mysql_error();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
//handles the name
$name = filterData($_POST["name"]);
if (empty($name)) {
$nameError = "please don't leave the name field blank";
}
//handles the email
$email = filterData($_POST["email"]);
if (empty($email)) {
$emailError = "please don't leave the email field blank";
}
//handles the subject
$subject = filterData($_POST["subject"]);
if (empty($subject)) {
$subjectError = "please don't leave this field blank";
}
$comments = filterData($_POST["comments"]);
}
$insertation = "INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', '', '$comments')";
$insertationQuery = mysql_query($insertation, $connection);
if (!$insertationQuery) {
echo "Could not process your information " . mysql_error();
} else {
echo "Thank you for submitting the information";
}
?>
原文由 johnbumble 发布,翻译遵循 CC BY-SA 4.0 许可协议
除了检查您的表设置以确认该字段设置为
NOT NULL
默认为CURRENT_TIMESTAMP
,您还可以通过以字符串格式写入 PHP 中的日期/时间值来插入它们与 MySQL 兼容。这将为您提供可以插入 MySQL 的字符串格式的当前日期和时间。