Php 在插入之前检查datetime字段

Php 在插入之前检查datetime字段,php,mysql,validation,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

我希望能够在插入另一条记录之前检查表中最新记录的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看起来如何?

您可以这样使用

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;

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

从`tablename`中选择MAX(`mydate`)作为mydate;
或
按“mydate”说明限制1从“tablename”顺序中选择“mydate”;
或者,如果您有一个名为id的主键自动递增列,则这可能是最快的:
按'id'说明限制1从'tablename'顺序中选择'mydate';

就个人而言,我最好将此逻辑移动到数据库中,例如创建触发器(在插入之前打开),或者在没有触发器的情况下,在插入之前检查此
TIMEDIFF(now(),ts)>'00:00:05'
inserting@k102实际上,我会把这个逻辑排除在数据库之外。数据库应该与防洪无关。还有DB句柄,这意味着您仍然需要连接到它,而保持连接数的减少通常是这种限制的一个原因。应该使用会话或SHM来处理它。反正速度快多了。太棒了,很高兴你发现它有用。谢谢你也接受了答案。
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';
}