如何将时间戳插入我的MySQL表中?

2022-08-30 13:03:11

在MySQL表中,我有一个名为date的字段,其类型称为时间戳,默认值为。但是,如果我在MySQL中将字段留空,则会出现错误。当我尝试在其中插入某些内容时,就像我收到日期一样。CURRENT_TIMESTAMPtime()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";
    }
    
?>

答案 1

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

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

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


答案 2

请尝试或功能CURRENT_TIME()now()

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"

或者你可以在这里尝试使用PHP函数:date

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

推荐