插入前检查datetime字段


Check datetime field before insert

我希望能够在插入另一条记录之前检查表上最新记录的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在上面的例子中是什么样子的?

首先查询数据库的最新日期时间。像这样的事情应该会奏效: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)首先使用此查询

获取最后记录日期值
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;