插入前检查日期时间字段

时间:2013-01-10 10:57:43

标签: php mysql validation

我希望能够在插入另一条记录之前检查我桌面上最新记录的 datetime 字段。当插入记录时,我用它来填充 datetime 字段:

$date = date("Y-m-d H:i:s");

至于现在我对其他字段进行了验证,但我想在 datetime 字段上添加验证。它应检查我的表上的最新记录,并检查 datetime 字段和$ date = date(“Y-m-d H:i:s”)之间的差异;如果差异是5秒或更短,它现在应该允许在表中插入新记录。将显示错误消息,如下所示:

    }else if(trim($checktime) == '') {
    $error = 'Please wait 5 seconds before insert'; 
   } if($error == '') { //Run the code

上面我的例子的$ checktime怎么样?

2 个答案:

答案 0 :(得分:2)

首先在数据库中查询最新的日期时间。像这样的东西应该做的伎俩: SQL:

SELECT MAX(`mydate`) AS mydate FROM `tablename`;
or
SELECT `mydate` FROM `tablename` ORDER BY `mydate` DESC LIMIT 1;
or if you have a primary key auto-increment column called id this may be fastest:
SELECT `mydate` FROM `tablename` ORDER BY `id` DESC LIMIT 1;

<?php
$last_insert_time = strtotime(); # Use the result from the database query as the parameter
$now = time();

# If the difference between the last inserted entry and the current time is less
# than five seconds perform an error action.
if (($now - $last_insert_time) < 5) {
    $error = 'Please wait 5 seconds before insert';
}

答案 1 :(得分:0)

你可以这样使用

1)首先使用此查询获取最后一个记录日期值

SELECT dateVal FROM tablename ORDER BY id DESC LIMIT 0, 1;

2)使用此

查找两个日期的差异
$timeFirst  = strtotime($dateVal);
$timeSecond = strtotime(date('Y-m-d H:i:s'));
$checktime= $timeSecond - $timeFirst;