时间戳表单表单提交到MySQL

Time stamping form form submits into MySQL

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

提交表单:

<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',但只需要知道它在哪个点为条目添加时间戳以及在哪里?

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

timeStampField TIMESTAMP DEFAULT CURRENT_TIMESTAMP

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

插入文档条目时尝试使用 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();
}