简体   繁体   中英

Update HTML table every 5 seconds with mySQL, and PHP?

I have a simple PHP page that sends a query to a mySQL database and displays the data onto a HTML table.

How can I get it to do this every 5 seconds? Currently it does this upon the page loading. The database will have changing data, so am trying to get the code to refresh every 5 seconds to keep the table updated.

How might I go upon doing this?

You need to use a client-side scripting language such as JavaScript to have a webpage do something after it has been served to a client.

Specifically, you will want to use timers and AJAX calls . You may also find the jQuery library useful for abstracting AJAX calls however it is not a requirement.

You need to use javascript ajax. For example ,

 <script>
 function loadXMLDoc()
 {
 var xmlhttp;
 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 (xmlhttp.readyState==4 && xmlhttp.status==200)
     {
     document.getElementById("myDiv").innerHTML=xmlhttp.responseText; // your div
     }
   }
 xmlhttp.open("GET","getdatabase.php",true); //your php file
 xmlhttp.send();
 }
 window.setInterval(function(){
   loadXMLDoc();
 }, 5000);

 </script>

Then in html , you must have a div with specified ID(myDiv) Fpr example:

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

Then in getdatabase.php you must fetch the value from the database and echo it out. For example,

 <?php
 $con=mysqli_connect("example.com","peter","abc123","my_db");// Check connection
 if (mysqli_connect_errno()) {
   echo "Failed to connect to MySQL: " . mysqli_connect_error();
 }

 $result = mysqli_query($con,"SELECT * FROM Persons");

 echo "<table border='1'>
 <tr>
 <th>Firstname</th>
 <th>Lastname</th>
 </tr>";

 while($row = mysqli_fetch_array($result)) {
   echo "<tr>";
   echo "<td>" . $row['FirstName'] . "</td>";
   echo "<td>" . $row['LastName'] . "</td>";
   echo "</tr>";
 }

 echo "</table>";

 mysqli_close($con);
 ?> 

Hope it works , see more at www.w3schools.com/

Use javascript timers. From there-on u can periodically run the SQL command to read the databases.

If this problem still arises, I can post some example code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM