我尝试修改长轮询代码以适应我的情况。 我想从mysql中计算总数,如果数字发生变化(增加或减少),它会通知我。
问题是while循环保持循环。我怎么能阻止它?我只需要在总和变化时收到通知。
<?php
include("db.php");
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$old_totalsum = $row['totalsum'];
}
?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
var old_totalsum =<?php echo $old_totalsum; ?>;
function waitForMsg(){
$.ajax({
type: "GET",
url: "poll.php?old_totalsum=" + old_totalsum,
async: true,
cache: false,
success: function(data){
var json = "eval(+(" + data + ")+)";
if(json['msg'] != "") {
alert(data);
}
old_msg_id = json['old_msg_id'];
setTimeout('waitForMsg()',1000);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
alert("error: " + textStatus + " (" + errorThrown + ")");
setTimeout('waitForMsg()',15000);
}
}); // end ajax
} //end waitformsg
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<div id="chat">
</div>
</body>
</html>
<----------------------------------------------------------->
poll.php
<----------------------------------------------------------->
<?php
include("db.php");
$old_totalsum = $_GET['old_totalsum'];
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
}
while($last_sum < $old_totalsum || $last_sum > $old_totalsum)
while($last_sum <= $old_totalsum)
{
usleep(1000);
clearstatcache();
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$last_sum = $row['totalsum'];
//echo $last_sum;
//return;
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $last_sum;
echo json_encode($response);
?>
<------------------------------------------->
答案 0 :(得分:0)
我期待这样的逻辑:
$latest_sum= -1;
// Loop until sum from DB is different from what was passed in
while( $latest_sum == -1 || $latest_sum!= $old_sum ){
$result = mysql_query("SELECT sum( r ) as totalsum FROM (SELECT colA, colB, COUNT( * ) AS r FROM product GROUP BY productid ) AS t");
while($row = mysql_fetch_array($result))
{
$lastest_sum = $row['totalsum'];
}
}
$response = array();
$response['msg'] = 'new';
$response['old_msg_id'] = $latest_sum;
echo json_encode($response);
如果需要很长时间才能更改,那么Apache(或运行PHP的任何内容)可能会取消该请求。这也将在db上运行大量查询,这是非常昂贵的。
所以最好将你的循环放在javascript中。它会调用一个只返回数据库中最新总和的函数。 javascript应该在每个请求之间等待一秒或更长时间。
如果数据库的性能仍然太难,那么php应该以某种方式每分钟缓存一次值并返回缓存的值。