【问题标题】:Time stamping form form submits into MySQL时间戳表单表单提交到 MySQL
【发布时间】:2015-07-12 19:30:02
【问题描述】:

我已经获得了将数据从表单输入到数据中所需的一切,但努力将其设置为时间戳或寻找最佳方法。

提交表格:

<form action="actions/newDocAdd.php" method="post">
    <input type="text" name="doc_title" id="doc_title" required="required" placeholder="Document Title"/><br />
    <input type="text" name="doc_content" id="doc_content" placeholder="Document Content"/><br/>
    <br><br> 
    <input type="submit" value="Create Document" name="submit"/><br />
</form>

<?php

if(isset($_POST["submit"])){
$hostname='localhost';
$username='******';
$password='******';

try {

$dbh = new PDO("mysql:host=$hostname;dbname=******",$username,$password);

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line

$sql = "INSERT INTO doc_list (doc_title, doc_content) VALUES ('".$_POST["doc_title"]."','".$_POST["doc_content"]."')";

if ($dbh->query($sql)) {
    header ('Location: ../docList.php');
}
else{
}

$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}

}
?>

我在数据库中有一个字段设置为 DATETIME,名为“doc_create”,但只需要知道它在哪个时间点为条目加上时间戳以及在哪里?

【问题讨论】:

    标签: php sql forms submit


    【解决方案1】:

    最好的点是表定义中字段的默认值。您必须按如下方式定义该字段:

    timeStampField TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    

    您也可以将字段类型定义为DATETIME 请注意,这适用于 mySql 版本 MySQL 5.6.5 及更高版本。

    【讨论】:

    • 我已将该字段默认为 DATETIME 但是我需要在从我的表单创建记录时添加时间戳?
    • 我进行了这些更改并添加了 NOW(),现在就像一个魅力一样,谢谢
    【解决方案2】:

    在插入文档条目时尝试使用 NOW()

    <form action="actions/newDocAdd.php" method="post">
        <input type="text" name="doc_title" id="doc_title" required="required" placeholder="Document Title"/><br />
        <input type="text" name="doc_content" id="doc_content" placeholder="Document Content"/><br/>
        <br><br> 
        <input type="submit" value="Create Document" name="submit"/><br />
    </form>
    
    <?php
    
    if(isset($_POST["submit"])){
    $hostname='localhost';
    $username='******';
    $password='******';
    $title = $_POST["doc_title"];
    $content = $_POST["doc_content"];
    try {
    
    $dbh = new PDO("mysql:host=$hostname;dbname=******",$username,$password);
    
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
    
    $stmt = $dbh->prepare("INSERT INTO doc_list (doc_title, doc_content,doc_create) VALUES (:title, :content, NOW())");
    $stmt->bindParam(':title', $title);
    $stmt->bindParam(':content', $content);
    if ($stmt->execute()) {
        header ('Location: ../docList.php');
    }
    else{
    ... // your else code
    }
    
    $dbh = null;
    }
    catch(PDOException $e)
    {
    echo $e->getMessage();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-27
      • 2019-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-25
      相关资源
      最近更新 更多