如何将mysql的COUNT()结果显示到网页并自动更新而不刷新网页?

时间:2016-08-30 01:12:12

标签: php mysql ajax

我有这个问题:

SELECT COUNT(*) FROM my_table;

我想在我的网页上显示它并自动更新它而不刷新网页。

HTML代码:

<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>

我也有这个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();
?>

我不知道如何在我的HTML中显示计数。我还想自动更新显示而不刷新网页,让我们说每30秒。

2 个答案:

答案 0 :(得分:0)

count.php

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

您的html文件现在可以包含

 <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>

有关$.ajax的更多信息; http://api.jquery.com/jquery.ajax/

答案 1 :(得分:0)

你应该使用post()Methode形式jquery和setTimeout()。

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <div class="container">
        <h5 id="count">/*mysql query result goes here*/</h5>
    </div>
    </body>
    <script>
        setTimeout(function(){
            $.post("Count.php",
               {get_count:true},
                function(result){
                    $("#count").html(result);
                }
             );
        },30000);
    </script> 
</html>

别忘了更改php文件。你需要检查POST ['get_count']是否是最好的,如果你想处理多个Post请求。