gpt4 book ai didi

php - 如何将 TIMESTAMP 插入到我的 MySQL 表中?

转载 作者:IT老高 更新时间:2023-10-29 00:09:49 24 4
gpt4 key购买 nike

在 MySQL 表中,我有一个名为日期的字段,其类型称为时间戳,默认值为 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";
}

?>

最佳答案

除了检查您的表设置以确认该字段设置为 NOT NULL 并默认为 CURRENT_TIMESTAMP,您还可以通过 PHP 插入日期/时间值以与 MySQL 兼容的字符串格式编写它们。

 $timestamp = date("Y-m-d H:i:s");

这将为您提供可以插入 MySQL 的字符串格式的当前日期和时间。

关于php - 如何将 TIMESTAMP 插入到我的 MySQL 表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37616760/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com