I'm creating a small browser game and recently I had a question about how to make a database value be manipulated (queried / updated) every second even with the user disconnected.
I have in my database a table called recursos
with columns ouro
and ouroPorSegundo
.
The way I managed to make it work is to create a page just for the server, using it setTimeout
to, every second, call a PHP page that updates the database.
Is this way to do it right? I think I may be overwhelmed when using this method several times (I use it to check if the troops / units have already returned to the base after an attack), and I need to keep a page open on the server to keep updating the data from all users.
Edit:
The game must work in the style of tribal wars
, ikariam
, they use some system that every second the database is changed, because you can receive an attack of another player, and depending on the second that receives the attack the Stolen gold has a different value.
I'm doing this on the server page:
$(function() {
getStatus();
});
function getStatus() {
$('div#status').load('getstatus.php');
setTimeout("getStatus()",1000);
}
getstatus.php:
$select = mysqli_query($conexao, "SELECT * FROM player_resources WHERE id = 1");
if (mysqli_num_rows($select) >= 1) {
while($row = mysqli_fetch_array($select)) {
$ouro_hora = $row['ouro_hora'];
}
$ouro_seg = $ouro_hora / 60 / 60;
}
$update = mysqli_query($conexao, "UPDATE player_resources SET ouro = ouro + $ouro_seg WHERE id = 1");
As I said it is functional, but the question is whether it is the right way to do it.