gloc gloc - 3 months ago 4
MySQL Question

How to display COUNT() result from mysql to a webpage and automatically update without refreshing webpage?

I have this query:

SELECT COUNT(*) FROM my_table;


And I want to display it in my webpage and automatically update it without refreshing the webpage.

HTML Code:

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<h5>/*mysql query result goes here*/</h5>
</div>
</body>
</html>


I also have this count.php:

<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "myDB";

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT COUNT(*) AS Count FROM my_table";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo $row['Count'];
$conn->close();
?>


I don't know how to display the count in my html. I also want to update the display automatically without refreshing the webpage, lets say every 30 seconds.

Answer

To do an ajax call to your count.php

$.ajax({
     url: "count.php",
     cache: false,
     success: function(html){
         $("#result").html(html);
     }
 });

Your html file can now contain

 <html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
 </head>
 <body>
  <div class="container">
   <h5 id="result">/*mysql query result goes here*/</h5>
  </div>
 </body>
</html>

More information on $.ajax; http://api.jquery.com/jquery.ajax/