0
如果在最近20秒内在sql上添加数据,我想追加一次新数据。如果在过去的20秒内在sql中添加一次数据,则会添加一次新数据
所以我在我的wall.php页面中使用了下面的脚本。
现在在我的server.php档案查询我创建为
$timestamp = date("Y-m-d H:i:s", time() - 20);
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='1012' AND `date` > '".$timestamp."' ORDER BY date DESC LIMIT 1") or die(mysqli_error($dbh));
我也试过这不行:
WHERE qazi_id='1012' AND `date` >= NOW() - INTERVAL 20 SECOND ORDER BY date DESC LIMIT 1
我的SQL日期格式为2015-02-25 19:45:28
但我得到的查询同样的数据在我使用$timestamp
的情况下也是在5分钟以上。
如果发布的时间是20:20:00,我的查询当前时间是 20:20:10,它将显示帖子。但如果我的查询的当前时间 是20:20:30(超过20秒后从发生时间),它会 不显示任何东西。
请给我一个指导方针来解决它“如果在最近20秒内在sql上添加了一次数据,就附加新数据”。
我的全代码在这里如下:
JS:
<script type="text/javascript" charset="utf-8">
function addmsg(type, msg){
$("#messages").append(
"<div class='msg "+ type +"'>"+ msg +"</div>"
);
}
function waitForMsg(){
$.ajax({
type: "GET",
url: "/server/server.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
addmsg("new", data);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function(){
waitForMsg();
});
</script>
Server.php
include("../db.php");
global $dbh;
header('Content-Type: application/json; charset=utf-8');
while (true) {
//fetch data
$timestamp = date("Y-m-d H:i:s", time() - 20);
$results = mysqli_query($dbh,"SELECT * FROM comments_lite WHERE qazi_id='1012' AND `date` > '".$timestamp."' ORDER BY date DESC LIMIT 1") or die(mysqli_error($dbh));
$rows = mysqli_fetch_assoc($results);
$data = $rows['description'];
//has data
if (!empty($data)) {
echo json_encode($data);
flush();
exit(0);
}
sleep(5);
}
请解释'在过去的20发现秒'。这听起来像你运行一个连续的搜索,并且你想要在过去的20秒中找到所有结果,这听起来有点奇怪。另一种解释是“在MySQL中启动搜索,20秒后停止并返回您找到的内容”,但也有点奇怪。你能澄清一下吗? – 2015-02-24 11:53:03
它不适用于你的日期格式。使用日期时间列类型。 – Marek 2015-02-24 11:58:16
@Jeremy Thille更新以上。谢谢你。 – joy 2015-02-24 12:00:31