Html auto refresh table

Chris Gunstone picture Chris Gunstone · Jun 29, 2011 · Viewed 14.9k times · Source

I wrote this simple code and this table which I have connected to mysql database. It fetches the data I inserted in my database what I want is for the page to automatically refresh on its own without having to refresh the whole page.
My Code:

<html>
    <head>
        <title>Whats Up?</title>
    </head>
    <body>
        <a href="Register.php">Register</a> <a href="login.php">Login</a>


<?php
    mysql_connect('localhost', 'root');
    mysql_select_db('summerinstitute');
    $query="SELECT * FROM students";
    $result=mysql_query($query);
    echo "<table border=\"1\">";
    while ($row = mysql_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>";
    echo $row['fname'];
    echo "</td>";
    echo "<td>";
    echo $row['lname'];
    echo "</td>";
    echo "<td>";
    echo $row['username'];
    echo "</td>";
    echo "<td>";
    echo $row['Email'];
    echo "</td>";
    echo "</tr>";}
    ?>
    </body>
</html>

Answer

Naftali aka Neal picture Naftali aka Neal · Jun 29, 2011

You need to use javascript and some ajax implementation to only refresh a part of the page.

For example with jQuery:

php page1.php:

<html>
    <head>
        <title>Whats Up?</title>
    </head>
    <body>
        <a href="Register.php">Register</a> <a href="login.php">Login</a>
        <?php include_once('page2.php')?>
    </body>
</html>

php page2.php:

<?php
    mysql_connect('localhost', 'root');
    mysql_select_db('summerinstitute');
    $query="SELECT * FROM students";
    $result=mysql_query($query);
    echo "<table border='1' id='tableID'>";
    while ($row = mysql_fetch_assoc($result)) {
    echo "<tr>";
    echo "<td>";
    echo $row['fname'];
    echo "</td>";
    echo "<td>";
    echo $row['lname'];
    echo "</td>";
    echo "<td>";
    echo $row['username'];
    echo "</td>";
    echo "<td>";
    echo $row['Email'];
    echo "</td>";
    echo "</tr>";}
    ?>

Javascript on page1.php (put it in the header):

<script type='text/javascript'>
   $(function(){
       $.get('page2.php',{},function(data){
           $('#tableID').replaceWith($(data));  
       });
   });
</script>