【问题标题】:Inserting DATETIME to SQL from PHP [duplicate]从 PHP 将 DATETIME 插入 SQL [重复]
【发布时间】:2017-08-26 02:50:52
【问题描述】:

我似乎无法将日期时间存储到数据库中。

public function add_post($username, $content) {
    date_default_timezone_set("Asia/Manila");
    $date = date("m/d/Y h:i A");
    $final = strtotime($date);
    $time_posted = date("m/d/Y h:i A", $final);

    $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";

        return $this->db->query($sql);
}

在数据库中看起来像这样 0000-00-00 00:00:00

这是我的帖子表:Posts table

【问题讨论】:

    标签: php mysql datetime


    【解决方案1】:

    日期时间字段的格式应为:

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

    【讨论】:

    • 谢谢。很高兴它奏效了。不过,一个小建议 - 与日期时间/时间戳无关。请查看MySQLiPDO Prepared Statements,以一种相当安全的方式编写查询。如果这是一个实时系统,那么它可能会通过互联网暴露给SQL Injection Attacks
    • 感谢您的建议:)
    【解决方案2】:

    为您提供此代码,

    public function add_post($username, $content) {
       date_default_timezone_set("Asia/Manila");
       $date = date("m/d/Y h:i A");
       $final = strtotime($date);
       $time_posted = date("Y-m-d H:i:s", $final);
    
       $sql =" INSERT INTO POSTS (username, post_content, time_posted)
            VALUES ('$username','$content','$time_posted')";
    
        return $this->db->query($sql);
    }
    

    【讨论】:

      【解决方案3】:

      MySQL 时间戳有一个固定的日期时间输入模式,即“Y-m-d H:i:s”,如果你想将日期时间插入数据库,请将模式转换为上述模式,然后尝试。它会工作的

      【讨论】:

        猜你喜欢
        • 2016-08-17
        • 1970-01-01
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-13
        • 2023-03-28
        • 1970-01-01
        相关资源
        最近更新 更多