问题
I'm a newbie, so be kind :)
What is the simplest solution for checking for, retrieving and using newly received data from a mysql database?
The database is being updated from an external api. Ideally I would get it as it arrives but using intervals could work too. On the first iteration and then once every 5 minutes if there is no new data meanwhile - do an action with the next entry of the array which might cause data to be updated within the next 5 min. But I want to make sure to stop everything if the new data has been received, and just perform some stuff in php.
what's the most simple solution? php vs jquery/ajax?
my proposed solution is in jquery:
<script>
var newdata = false;
if(newdata === false){
setTimeout (function(){
$.each(array, function(){
$.post('checkdb.php',data,function(resp){
if(resp){
newdata=resp;
return newdata;
}
else{
$.post('doaction.php',data);
// cause a potential update within the next 5 min
}
});
});
}, 300000);
}
else{
// move newdata back to php and (then) do something with response
}
</script>
Thanks! :)
回答1:
My solution in the end is indeed in php and not ajax (there is really no need for client side in this situation).
Here's the outline:
<?php
while (something is true){
//do stuff
flush(); // execute the stuff you did until now
sleep(300); // wait 5 min
// now check database and retrieve new data, if any, and insert into $result
if (isset($result)){
//do stuff with the $result
break; // get out of the loop
}
}
?>
回答2:
Don't use such logic on client side. JavaScript could be easily manipulated/changed. Someone could replace the interval with much shorter one and stress the server. Read about Comet, use it for waiting for the results from the server. On the server side do all the logic: implement database polling (with interval, as you wish), and, when needed, push the data to the browser/stop polling/do whatever you want.
来源:https://stackoverflow.com/questions/8621339/timely-interval-to-retrieve-data-from-db-and-stop-when-the-data-arrives