php 更新数据库时如何刷新页面?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4629642/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I refresh a page when a database is updated?
提问by omc11
How can I detect the latest updates made to a database and silently refresh a page when a change occurs?
如何检测对数据库所做的最新更新并在发生更改时静默刷新页面?
Let's say the database access looks like:
假设数据库访问如下所示:
$host = "localhost";
$username = "root";
$password = "root";
$db = mysql_connect($host,$username,$password) or die(mysql_error());
mysql_select_db('ccr') or die(mysql_error());
Any ideas and samples would be appreciated. Thank you.
任何想法和样品将不胜感激。谢谢你。
采纳答案by Kalessin
This is how I recently implemented a solution using jQuery.
这就是我最近使用 jQuery 实现解决方案的方式。
PHP increments a field in the database every time a significantupdate occurs.
每次发生重大更新时,PHP 都会增加数据库中的一个字段。
<?php
// Call this function when data changes
function update_clients()
{
mysql_query( "UPDATE pageGen SET id = id + 1 LIMIT 1" );
}
// Call this function to get the ID to pass to JavaScript
function get_update()
{
$result = mysql_query( "SELECT id FROM pageGen LIMIT 1" );
$update = mysql_result( $result, 0, 'id' );
return $update;
}
?>
When the page is initially loaded, populate a JavaScript variable with a number from the database:
最初加载页面时,使用数据库中的数字填充 JavaScript 变量:
<script type="text/javascript">
var pageGenID = 25218603 // generated by PHP
var processUpdate = function( response )
{
if ( pageGenID < response )
{
replace_current_data_with_new_via_ajax();
pageGenID = response;
}
}
// Compare our Page Generate ID against that of the server
var checkUpdates = function()
{
serverPoll = setInterval( function()
{
$.get('script_to_return_latest_pageGenID.php',
{ lastupdate: 1 },
processUpdate, 'html');
}, 10000 )
};
// Check for updates every 10 seconds
$( document ).ready( checkUpdates );
</script>
回答by Ofir Attia
Here is what I did and used the answer you marked but I think there is a few things to change there. In the main page ( that you want to refresh if something changed in the database). I created a table in my database called setting, in this table i created a row that called rowCounter. the rowCounter is being updated when the numbers of rows in the table you check has been changed. so my code split in two blocks. one that giving me the number from the setting > rowCounter and the second is the script that give me the current number in the table. if they are not equal then I refresh the page.
这是我所做的并使用了您标记的答案,但我认为那里有一些需要更改的地方。在主页中(如果数据库中的某些内容发生更改,您希望刷新)。我在我的数据库中创建了一个名为 setting 的表,在这个表中我创建了一个名为 rowCounter 的行。当您检查的表中的行数已更改时,正在更新 rowCounter。所以我的代码分成两个块。一个给我设置> rowCounter 中的数字,第二个是给我表中当前数字的脚本。如果它们不相等,那么我刷新页面。
so this is the first file you need
script_to_return_latest_pageGenID.php
所以这是你需要的第一个文件
script_to_return_latest_pageGenID.php
// here you will make you connection query.
$result = mysql_query( "SELECT rowCounter FROM setting WHERE `id`='2'" );
$update = mysql_fetch_assoc($result);
echo implode($update);
$count=mysql_query("SELECT `id` FROM log_".$datestamp."")or die(mysql_error);
$number = mysql_num_rows($count);
//echo $number;
$countFromSetting=mysql_query("SELECT `rowCounter` FROM setting WHERE id='2'")or die(mysql_error);
$numberFromSetting=implode(mysql_fetch_assoc($countFromSetting));
if($number != $numberFromSetting)
{
mysql_query("UPDATE setting SET `rowCounter`='$number' WHERE `id`='2'")or die(mysql_error);
}
In the main page you will write the two blocks of code I provided and you should put it before the script.
在主页面中,您将编写我提供的两个代码块,并将其放在脚本之前。
$countFromSetting=mysql_query("SELECT `rowCounter` FROM setting WHERE id='2'")or die(mysql_error);
$numberFromSetting=implode(mysql_fetch_assoc($countFromSetting));
After this code you put the script that will query every few seconds the php script, check if the numbers are not equal it will refresh the page.
在此代码之后,您将每隔几秒钟查询一次 php 脚本的脚本,检查数字是否不相等,它将刷新页面。
var pageGenID = "<?php echo $numberFromSetting; ?>";
var processUpdate = function( response ) {
var x=response;
//console.log(pageGenID); by removing the remarks you will see the compared numbers all the time.
//console.log(x);
if ( pageGenID != x )
{
//replace_current_data_with_new_via_ajax();
pageGenID = response;
window.location.reload();
}
}
var checkUpdates = function()
{
serverPoll = setInterval( function()
{
$.get('script_to_return_latest_pageGenID.php',
{ lastupdate: 1 },
processUpdate, 'html');
}, 5000 ) };
$( document ).ready( checkUpdates );
回答by Scott Fulkerson
It would seem like you could use something like this, using a while loop. This won't work for massive amounts of users (will probably crash PHP or SQL), and at some point you will have to reset the count variables in your script.:
看起来你可以使用这样的东西,使用一个 while 循环。这对大量用户不起作用(可能会使 PHP 或 SQL 崩溃),并且在某些时候您将不得不重置脚本中的计数变量。:
<?PHP
//initialize the variables somewhere before any of the following. do not use these
//variables for any other purpose other than the refresh routines:
$a==0;
$b==0;
//First design code within a function to refresh the database a single iteration.
fuction refresh(){
insert code here to output database;
}
//Now, call function refresh in a loop at the spot in the code
//where we want to refresh the database. where $b here is equal to
//the number of times you want the database to automatically refresh
//before having to reset the variables to 0.
$b==1
while ($b!==$a){
refresh();
$a==$a+1;
}
?>
回答by Qix - MONICA WAS MISTREATED
Strictly speaking, this is not possible. MySQL does not fire triggers back to PHP if something is changed. It's just not possible. Also, MySQL operates using sessions, so even if it could report a change in the database, you'd have to use a persistent connection in order for you to be able to access that sort of trigger.
严格来说,这是不可能的。如果某些内容发生更改,MySQL 不会将触发器返回给 PHP。这是不可能的。此外,MySQL 使用会话进行操作,因此即使它可以报告数据库中的更改,您也必须使用持久连接才能访问那种触发器。
Now, if you want to execute select statements to detect a change in the database, that's different. Depending on how "new" you want your code to be (depending on how compatible you'd like it to be) you can use any one of the following to "poll" a PHP page to check for changes: Comet, AJAX, a forever frame, or HTML5's new WebSocket
class.
现在,如果您想执行 select 语句来检测数据库中的更改,那就不同了。根据您希望代码的“新”程度(取决于您希望它的兼容性如何),您可以使用以下任何一种来“轮询”PHP 页面以检查更改:Comet、AJAX、永远的框架,或 HTML5 的新WebSocket
类。
While other say use the client to detect a change through variables like a database version stored in javascript, I'd advise that you leave that server sided simply because people who know how to inject javascript will be able to change that value, which may produce undesired or even malicious results (even, depending on how that value is used, MySQL injections).
虽然其他人说使用客户端通过诸如存储在 javascript 中的数据库版本之类的变量来检测更改,但我建议您将该服务器留在一边,因为知道如何注入 javascript 的人将能够更改该值,这可能会产生不希望的甚至是恶意的结果(甚至,取决于该值的使用方式,MySQL 注入)。
回答by shaunhusain
I believe you'd have to poll the database when you use PHP, PHP doesn't exist in a long running process as in the case of a Java container where the Java web application could create a persistent connection (in theory) you'll likely need to employ some sort of polling mechanism by which I mean setup a timer in Javascript or whatever your client code is to periodically make the request, in terms of increasing efficiency for this if need be you could create a flag on the users table and set the flag to indicate that the database has been invalidated since the user last polled, then your first check would be if invalidation has happened since that user last updated rather than sending everything to everyone all the time. Alternatively I think you'd need to abandon PHP for this task.
我相信您在使用 PHP 时必须轮询数据库,PHP 不存在于长时间运行的进程中,就像 Java Web 应用程序可以创建持久连接(理论上)的 Java 容器一样可能需要使用某种轮询机制,我的意思是在 Javascript 或任何您的客户端代码中设置一个计时器来定期发出请求,如果需要的话,您可以在用户表上创建一个标志和设置标志以指示自用户上次轮询以来数据库已失效,那么您的第一次检查将是自该用户上次更新以来是否发生了失效,而不是一直将所有内容发送给所有人。或者,我认为您需要为此任务放弃 PHP。
回答by Poelinca Dorin
Ideea:
想法:
When you render a page with php , you can pass a js variable witch has keeps a "current database revision" ( a number ) . On the page you make an ajax call once every 30 seconds a witch recives a new current database revision so to speak . You test for those 2 and if the one you got from the ajax call is higher then it means you need to reload the page .
当您使用 php 呈现页面时,您可以传递一个 js 变量,女巫保留了“当前数据库修订版”(一个数字)。在页面上,您每 30 秒进行一次 ajax 调用,女巫可以这么说来接收一个新的当前数据库修订版。您测试了这 2 个,如果您从 ajax 调用中获得的那个更高,则意味着您需要重新加载页面。
On the server side you need a table to store the current revision , everytime you make a query from php you set the current revision +1 ( in the revision database table ) . When you receive an ajax call from a client you read that number from the database and you pass it on to the cilent . You can setup a cronjob that will reset the counter every day .
在服务器端,您需要一个表来存储当前修订,每次从 php 进行查询时,您都会设置当前修订 +1(在修订数据库表中)。当您收到来自客户端的 ajax 调用时,您从数据库中读取该号码并将其传递给 cilent 。您可以设置一个每天都会重置计数器的 cronjob。