How can I show database value in real time?

Asked

Viewed 1,357 times

1

I’m a beginner in php, let alone js. I would like to take a count of how many users are registered in my database, but in real time using ajax. I have tried in many ways, but without success. for now I have only in code:

$sql = "SELECT * FROM usuarios";
$query = mysql_query($sql);
$conta = mysql_num_rows($query);

the result that comes from $account is what I want to put in a <span id="users"</span> only if I simply put one echo $conta within span, it will not be in real time the value that will come out... "logica' would be, in a file have the query with the count of lines of the table users, and in another page that has the span keep requesting the value that comes from the variable $account.

What I need:

Show in real time using ajax the value of a string that counts how many rows are in the "users" table in a <span id="users"></span>

  • You will need a real-time database, which is not the case with Mysql, search for Firebase, must meet your needs

  • Could use Ajax requesting seconds to seconds.

  • Well, I meant using ajax... but I don’t know how I can do this

2 answers

2


You can use Ajax, but it’s not quite in real time. In the example below, requests are called every 2 seconds (you can change the time to more or less, but the shorter the time, you can overload the server with requests followed in a short time. Evaluate that).

function ajx(){
   var ajax = new XMLHttpRequest(); // cria o objeto XHR
   ajax.onreadystatechange = function(){
      // verifica quando o Ajax for completado
      if(ajax.readyState == 4 && ajax.status == 200){
         document.getElementById("users").innerHTML = ajax.responseText; // atualiza o span
         setTimeout(ajx, 2000); // chama a função novamente após 2 segundos
      }
   }
   ajax.open("GET", "pagina.php"); // página a ser requisitada
   ajax.send(); // envia a requisição
}
ajx(); // chama a função

Substitute pagina.php by the page where you are doing the echo.

  • It worked! Thank you.

  • AP will stay on one page and see if there are new records every 2 seconds? Waste of resources. A little iframe with link update

  • @Leocaracciolo Pois eh... how would you do it without making requests every now and then?

  • @Leocaracciolo cool, but what if the guy doesn’t want to keep clicking to update?

  • Ai do what you told, rs

0

I’ll start by putting my finger on what I think is wrong.
What reason would anyone have to show only the amount of registrants?

I think I’m wrong.I think I want to count users with a given name if it is : "IS WRONG"

$sql = "SELECT * FROM usuarios";
$query = mysql_query($sql);
$conta = mysql_num_rows($query);

If I’m right, you’ll have some discretion to tell me... "CORRECT"
Put one in your html
<div id="user"></div>
and a field responsible for rescuing its criteria

<input type="text"  placeholder="Digite o nome da cidade"name="Campo" id="Campo" onchange="PgReal(this.value);/>

The function is executed OnChange When you change the value of the E field you will return the values : Pay attention to that = php? Field file name

$variavelCampoNome=$_GET['CampoNome'];
$sql = "SELECT * FROM usuarios WHERE `Coluna` LIKE '%$variavelCampoNome%'";
if ($Resultado = mysql_query($sql)){ // Se ele conseguir executar
$conta = mysql_num_rows($Resultado);//faz a contagem
if ($conta==0){ //se FOR IGUAL A ZERO
echo 'Nenhuma Informação encontrada com esse criterio';
}else{ //Mostra a quantidade SE FOR DIFERENTE DE ZERO
echo '<span id="users">.$conta</span>';
while($Linha = mysql_fetch_array($Resultado)) {

//Criterios para exibir 
$VariavelColuna=$Linha[ColunaExibir];
echo $VariavelColuna;

}

}

Now the function .

function PgReal(str) {

    if (str == "") {
return;
    } else { 
        if (window.XMLHttpRequest) {
            // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else {
            // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("user").innerHTML = this.responseText; //Copia a resposta Para o div id=user
            }
        };
        xmlhttp.open("GET","Arquivo.php?CampoNome="+str,true);//Exececuta o chamado usando o valor do campo que você colocou o botao ONCHANGE
        xmlhttp.send();
    }

}

I THINK THAT’S WHAT YOU REALLY WANTED. MORE INTERNET FOR THIS. EDIT HOW AND WHERE YOU FIND BEST! Good luck

Browser other questions tagged

You are not signed in. Login or sign up in order to post.