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

新手上路,请多包涵

在 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 许可协议

阅读 583
2 个回答

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

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

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

原文由 shamsup 发布,翻译遵循 CC BY-SA 3.0 许可协议

您可以尝试 CURRENT_TIMESTAMP() function 同时传递 DML 查询。

原文由 Odeonus.com 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题