• Advertisement
Sign in to follow this  

problem with server loop push php

This topic is 417 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm not getting by code to work The result should be 125
150
175
And this always gives  this 125 125 125 125

don´t know where is the problem can someone help-me
Follow the code

server

<?php

require_once ('configurations/config.php');

// arquivo cujo conteúdo será enviado ao cliente

//$dataFileName = 'data.txt';


$timestart=time();
$PDO = new PDO('mysql:host=localhost;dbname=game', 'root','');

if(isset($_POST ['timestamp'])){

    $timestamp=$_POST [ 'timestamp' ];

}
else {
    $tempo=$PDO->prepare("SELECT NOW() as now");
    $tempo->execute();
    $row=$tempo->fetchObject();
    $timestamp=$row->now;
}
$sql = $PDO->prepare("SELECT cidade.ouro,cidade.madeira,cidade.metal,cidade.pedra,cidade.energia, cidade.comida,cidade.petrolio FROM users INNER JOIN cidade ON users.cod_user=cidade.cod_user WHERE cidade.timestamp>'$timestamp'AND users.username='admin';");

 $newdata = false;
 $notificacoes=array();
 while (!$newdata &&(time()-$timestart)<20) {
     $sql->execute();
 while ($row=$sql->fetchAll(PDO::FETCH_ASSOC)) {

     $notificacoes=$row;
        $newdata=true;
 }  
 usleep(500000);  
 } 
 $tempo=$PDO->prepare("SELECT NOW() as now");
    $tempo->execute();
    $row=$tempo->fetchObject();
    $timestamp=$row->now;
    $data= array('notificacoes'=>$notificacoes,'timestamp'=>$timestamp);
    echo json_encode($data);
    exit();
?>

cliente

$(function(){
notificacoes();
});
function notificacoes(timestamp){
    var data={};
    var resultado=0;
            var soma=2;
            var valor=25;
    if(typeof timestamp!='undefined')
    data.timestamp=timestamp;
    $.post('server.php',data,function(res){
        for(i in res.notificacoes ){

            resultado=+res.notificacoes[i].ouro+valor;

            $('#response').append(resultado);
        }

        notificacoes(res.timestamp);
    },'json');

}
<html>

	<head>

		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

		<script type="text/javascript" src="dist/js/client.js"></script>

	</head>

	<body>

		<h3>Conteúdo</h3>

		<div id="response" name="response"></div>

	
	</body>

</html>

Share this post


Link to post
Share on other sites
Advertisement
I'm really confused.

Why do you query the database just to get the current timestamp where strftime() does exactly the same thing?

I think it's related to the variable $row being used three times, each use overwriting the last.

The code is quite confusing though, especially to an English speaker, what do the column names and table names mean?

Share this post


Link to post
Share on other sites
Looking over the code, it seems you are attempting to server new messages, if any.
A few things:
  • There’s no need to query the database for the current time— use PHP’s time() instead.
  • Sleeping on the sever is bad. The frontend hangs until the server completes the request. There are tricky ways around this with long polling, but it can be avoided. Sending an empty array immediately to indicate no new notifications should be acceptable.
  • Your notifications are an array, use $notificacoes []= $row; to append.
  • It’s generally a good idea to remove the closing tag ?>, as it can accidentally introduce any text after it with your response stream.
  • The notificacoes function on the frontend does not have any limiter, and should include some sort of setTimeout to regulate how often it checks the server for messages.
Couple of other things you may want to consider:
  • If this is a JSON API, consider setting the content type by calling header('Content-Type: application/json')
  • Consider using http_response_code to set the default status code to “500 - Internal Server Error”, and set it to “200 - OK” once you’ve sent the response. (Output buffering may be required)
  • Or, setup proper error handling and exception handling to catch and prepare a proper error response.
Edited by fastcall22

Share this post


Link to post
Share on other sites

finaly i find the soluction

<html>

	<head>

		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

		
	</head>

	<body>
<script language="JavaScript">
$(function(){
notificacoes();
});
function notificacoes(timestamp){
	var data={};
	var resultado=0;
			var valor=25;
	if(typeof timestamp!='undefined')
	data.timestamp=timestamp;
	$.post('server.php',data,function(res){
		for(i in res.notificacoes){
			
			resultado=+res.notificacoes[i].ouro+valor;
			$.get('soma.php?c='+resultado);
			 //location.href ="soma.php?c="+ resultado;
			
		}
		  
		notificacoes(res.timestamp);
	},'json');
	
}

	</script>
	</body>

</html>

soma.php

<?php
//Sessões
session_start();
//Acesso a BD
require_once ('../configurations/config.php');
// algumas funcoes
require_once ('../configurations/functions.php');

//Array para erros de validacao
$errmsg_arr = array();

//flag de validacao
$errflag = false;

//Connect to mysql server
$link = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$link) {
	die('Falha na ligacao à BD: ' . mysql_error());
}
//"Limpar" os valores recebidos do formulario via POST
//$login = clean($_GET['c'], $link);

$qry = "UPDATE cidade SET ouro='". $_GET['c']. "' where cod_cidade='1'";
$result = $link -> query($qry);
 if($result) { 
     header("location:ola.php");
    } else { 
         echo("nicht ok"); 
    } 


Edited by Landi20

Share this post


Link to post
Share on other sites
You have a SQL injection vulnerability there. Consider what an attacker could write in "c" GET parameter.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement