2015-05-03 81 views
1

我已經擁有了將我的數據輸入到表單中的數據所需的所有東西,但卻努力使其獲得時間戳或尋找最佳方法。時間戳表單提交到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(); 
} 

} 
?> 

我有DB中的一個元素被設置爲DATETIME名爲「doc_create」只是需要一些想法,此時將其時間戳的條目,在哪裏呢?

回答

2

最好的一點是表格定義中字段的默認值。你必須定義字段如下:

timeStampField TIMESTAMP DEFAULT CURRENT_TIMESTAMP 

還可以定義字段類型爲DATETIME 通知,這將對於MySQL版本的MySQL 5.6.5和更高的工作。

+0

我已經默認領域爲DATETIME但我需要添加時間戳當記錄會從我的形式創造的呢? – coder123

+0

我做了這些改變,並添加NOW(),現在像一個魅力,謝謝你 – coder123

1

嘗試使用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(); 
}