如何在SQL数据库中提交日期和时间表?

时间:2013-06-28 15:27:06

标签: sql

$sql="INSERT INTO Persons (Name, Email, Telephone, PensionPot, BestTime)
VALUES
   ('$_POST[Name]','$_POST[Email]','$_POST[Telephone]','$_POST[PensionPot]','$_POST[BestTime]'    )";

if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}

    ?>

上面的代码是一个提交给sql数据库的表单但是在数据库中我希望能够看到表单提交的日期和时间?我该怎么做?

3 个答案:

答案 0 :(得分:4)

您可以使用CURRENT_TIMESTAMP

$sql="INSERT INTO Persons (Name, Email, Telephone, PensionPot, BestTime, your_datetimefieldname)
VALUES ('$_POST[Name]','$_POST[Email]','$_POST[Telephone]','$_POST[PensionPot]','$_POST[BestTime]', CURRENT_TIMESTAMP)";

答案 1 :(得分:0)

假设该字段被称为submissiondate,您的行将是:

$sql="INSERT INTO Persons (Name, Email, Telephone, PensionPot, BestTime,submissiondate)
VALUES ('$_POST[Name]','$_POST[Email]','$_POST[Telephone]','$_POST[PensionPot]','$_POST[BestTime]',CURDATE()    )";
编辑:对不起,我错过了你问题的“时间”部分。然后你可以使用:

$sql="INSERT INTO Persons (Name, Email, Telephone, PensionPot, BestTime,submissiondate)
    VALUES ('$_POST[Name]','$_POST[Email]','$_POST[Telephone]','$_POST[PensionPot]','$_POST[BestTime]',CURRENT_TIMESTAMP()    )";

请注意,执行数据库查询非常不安全,因为没有监视输入。你应该使用准备好的陈述!

答案 2 :(得分:0)

或者,您只需将数据库中列的默认值设置为当前时间戳即可。这样您就不必担心代码总是插入当前时间戳。

ALTER TABLE yourTable ADD COLUMN created timestamp DEFAULT CURRENT_TIMESTAMP /*and optionally:*/ ON UPDATE CURRENT_TIMESTAMP;