Select a Mysql table inside a PHP file without refresh

Asked

Viewed 1,379 times

2

Select Mysql database data inside a PHP file without refresh.

Example:

<?php
// Essa select abaixo tem que buscar a cada 5 segundos sem atualizar a página
$selecionaTabela = mysql_query("SELECT * FROM nomeTabela")or die(mysql_error());
// Fecha Select

$verifica = mysql_num_rows($selecionaTabela);
if($verifica >= 1){
   echo "Vai exibir os conteúdos aqui...";
}
?>

1 answer

4

You should use Javascript (AJAX) to display the data without having to reload the main page. I suggest using the jQuery library to facilitate interaction of AJAX requests.

1) Separate the file containing the query and mount the data view ajax.php

<?php
// Essa select abaixo tem que buscar a cada 5 segundos sem atualizar a página
$selecionaTabela = mysql_query("SELECT * FROM nomeTabela")or die(mysql_error());
// Fecha Select

$verifica = mysql_num_rows($selecionaTabela);
if($verifica >= 1){
   $dados = mysql_fetch_array($selecionaTabela);
   print_r($dados);
}

2) In the main file, which you want to display the data, make the AJAX request to the file containing the query (ajax.php)

<!DOCTYPE html>
<html>
<head>
    <title>Exibe dados</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(function(){
            //chama a função atualizaDados daqui à 5000ms (5s)
            window.setTimeout(atualizaDados, 5000);
            function atualizaDados() {
                //carrega o conteúdo do arquivo "ajax.php" para dentro da div#exibeDados
                $("#exibeDados").load('ajax.php');
                //para perpetuar a chamada da função sempre a cada 5s
                window.setTimeout(atualizaDados, 5000);
            }
        });
    </script>
</head>

    <body>
        <div id="exibeDados">
        </div>
    </body>

</html>
  • I did it the way you put it above, but in Chrome browser the images keep flashing! And in Firefox Mozilla does not blink. Here’s the link I made: http://wesleyk.com.br/timeline.php

  • I imagine it "blinks" because the code overrides the content of <div> with new tags <img>, making the src they are loaded every time they are inserted. I imagine that in Mozilla does not appear to "blink" because the images are already cached, the upload is imperceptible.

  • Got it, it’s just that I’m making a Timeline, and it would be like facebook, when there’s new content will appear without refresh on the page

Browser other questions tagged

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