>我有一个看起来像这样的sql查询:
<?php
include("settings.php");
$sql = conn->query("SELECT * FROM table LIMIT 1");
$content = $sql->fetch_assoc();
$id = $content['id'];
/* PHP Operations here. */
?>
现在,我希望能够每隔 5 分钟重复一次此 sql 查询,因为表内容会发生变化。我该怎么做?有没有办法在javascript或ajax脚本中执行sql请求?
如果您只想刷新内容,请在 settimeout() 中使用 AJAX 调用。
解决方案
使用 cron 作业。如果您显示的文件是"/var/www/some/file.php",则只需以运行Web服务器的用户身份执行以下命令(例如,"www-data"或"apache"):
{
# Will output to stdout the current user's crontab
crontab -l;
# Add a line to execute the php script every 5 minutes
echo '*/5 * * * * '"$(which php5) /var/www/some/file.php";
} | crontab - # The current user's crontab will be replaced by stdin
假设
- 你正在使用Linux。
- 您正在使用 apache httpd。
背景
PHP Web应用程序是由 Web 服务器运行以响应 HTTP 请求的 PHP 脚本。这里需要的是运行 PHP 脚本,不是为了响应 HTTP 请求,而是为了响应时间事件,例如,自上次运行以来已经过去了 5 分钟。
好吧,根据问答,真正的问题会有这样的解决方案:
文件
- 你有一个用户直接请求的PHP文件,我称之为"/index.php",位于"/var/www/index.php"。这有页面的呈现和一些javascript。
- 你有第二个PHP文件,它是由用户间接请求的,我称之为"/bg.php",位于"/var/www/bg.php"。此文件的内容仅具有更新数据库的例程,并返回 javascript 代码或其他内容。
索引.php
在这里,您将拥有类似以下内容:
<script type="text/javascript">
/* Have jquery included before */
function poll_the_server(){
/* Get the data from the server with ajax */
var jqxhr = $.ajax( "/bg.php" )
.always(function(){
/* Prepare the next run */
setTimeout(poll_the_server, 300);
})
.done(function(){
/* Succeded: Do whatever you want with your data */
})
.fail(function(){
/* Error: you may ask the user what to do */
});
}
/* Do the first call */
setTimeout(poll_the_server, 300);
</script>
编辑:
引用
http://api.jquery.com/jquery.ajax/