Display real-time data [duplicate]

-1

I'm trying to display data taken directly from my database with this script :

<script>
         setInterval( function contaUser(){
              document.write,("<?php
                   $sql = "SELECT Count(id) as c FROM tb_usuario";
                   $result = $con->query($sql);
                   $row = $result->fetch_assoc();
                    echo $row['c'].' Usuários';
               ?>");
               },2000 );
 </script>

I already included in the file all connection data and etc ... I would like to display this data in a div, "card" style ... Could you tell me what is wrong?

    
asked by anonymous 20.08.2018 / 15:03

1 answer

0

In javascript call via ajax the PHP page that executes SELECT and returns the desired result showing it in <div id="qqId"></div> .

<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script><divid="qqId"></div>
<script>

$( document ).ready(function() {
    var tempo = 2000; //Dois segundos

    (function selectNumUsuarios () {
        $.ajax({
          url: "selectNumUsuarios.php",
          success: function (n) {
              //essa é a function success, será executada se a requisição obtiver exito
              $("#qqId").text(n);
          },
          complete: function () {
              setTimeout(selectNumUsuarios, tempo);
          }
       });
    })();
});


</script>

selectNumUsers.php

<?php
$mysqli = new mysqli("localhost", "USUARIO", "SENHA", "Nome_DB");

/* checa conexão */
if (mysqli_connect_errno()) {
    printf("Conexão falhou: %s\n", mysqli_connect_error());
    exit();
}

if ($result = $mysqli->query("SELECT id FROM cadastro")) {

    /* determina o número de linhas retornadas */
    $numUsuarios = $result->num_rows;

    printf($numUsuarios." Usuarios");

    $result->close();
}

/* fecha a conexão */
$mysqli->close();
?>
    
20.08.2018 / 17:18