【问题标题】:How to add a timestamp of a prepared stmt to mysql database when code is run? [duplicate]运行代码时如何将准备好的stmt的时间戳添加到mysql数据库? [复制]
【发布时间】:2020-06-03 00:20:02
【问题描述】:
$stmt = $conn->prepare("INSERT INTO users (username,created) VALUES (?,?)");
$stmt->bind_param("ss", $_POST['username-reg','whatdoiputhere?']);
$stmt->execute();

我想添加一个“现在”日期/时间戳,它也可以同时插入,以便我可以跟踪用户何时创建帐户。是否有我需要编写/参考的函数来获取当前日期?还是有一个我只需要参考的已知函数?我是php新手,对不起

【问题讨论】:

    标签: php mysql sql timestamp prepared-statement


    【解决方案1】:

    您可以利用 MySQL 的 timestamp initialization feature

    这通过使用default current_timestamp 选项将timestamp 列添加到表中来工作:

    create table users (
        user_id int primary key auto_increment,
        username varchar(50),
        ts_created timestamp default current_timestamp
    );
    

    有了这个设置,您就不必再担心该列了。插入时忽略它,数据库会根据需要自动设置:

    $stmt = $conn->prepare("INSERT INTO users (username) VALUES (?)");
    $stmt->bind_param("ss", $_POST['username-reg']);
    $stmt->execute();
    

    注意:如果您还希望在记录被修改时更新时间戳,可以在列的定义中添加on update current_timestamp

    【讨论】:

      【解决方案2】:

      您可以使用NOW()

      $stmt = $conn->prepare("INSERT INTO users (username,created) VALUES (?, NOW())");
      $stmt->bind_param("s", $_POST['username-reg']);
      $stmt->execute();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-04
        • 1970-01-01
        • 1970-01-01
        • 2015-12-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多