从数据库刷新数据(PHP)

时间:2016-11-18 10:25:41

标签: php ajax

所以,我在下面有这个代码从我的数据库中获取数据,但我希望这些数据能够刷新'每隔5秒钟,以便在数据库中放入符合规格的新内容时显示。 (我不希望页面为此刷新,只有数据...)

$sql = "SELECT * FROM items WHERE reference = '1' ORDER BY datePosted asc LIMIT 5";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  while($row = $result->fetch_assoc()) {
      $title = $row["titel"];
      $description = $row["description"];
  }
} else {
    echo "Nothing found";
}

我一直在寻找AJAX和PHP的方法来做到这一点,但我似乎没有想出来......任何帮助/信息都表示赞赏!

3 个答案:

答案 0 :(得分:1)

你可以使用这样的东西;

<div id='contentToUpdate'></div>


<script type="text/javascript">


    setInterval(function(){
        LoadContent(); // this will run after every 5 seconds
    }, 5000);


    function LoadContent(){

        $.ajax({

            type:"POST",
            url: "/path/to/script.php",
            data: {GenerateContent: true, PostName2: 'value2'},

            success: function(result){

                $("#contentToUpdate").html(result);

            }, error: function(result){

                alert('something went wrong');

            }, complete: function(result){

                // fires regardless of above

            }

        });

    }

</script>

在php文件中,收到Ajax请求,你可能会有这样的东西;

    if(isset($_POST['GenerateContent'])){


        $aResults = array();

        $sql = "SELECT title, description FROM items WHERE reference = '1' ORDER BY datePosted asc LIMIT 5";
        $result = $conn->query($sql);

        while($row = $result->fetch()){
            $aResults[] = array('title' =>$row['title'], 'description' => $row['description']);
        }


        // if there are results output them
        if(!empty($aResults)){

            // foreach result
            foreach ($aResults as $iKey => $aResult) {
                echo "<p>";
                echo "Title: ".$aResult['title']."<br>\n";
                echo "Description: ".$aResult['description']."<br>\n";
                echo "</p>";
            }

        }else{
            echo 'No results have been loaded';
        }


        exit;
    }

答案 1 :(得分:0)

使用jQuery:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
setInterval(function()
{ 
    $.ajax({
      type:"POST",
      url:"path/to/script.php",
      success:function(data)
      {
          //do something with response data
      },
      error:function(e){
         console.log("Error Occurred");
      }
    });
}, 5000);//time in milliseconds 
</script>

答案 2 :(得分:0)

使用jQuery你可以尝试这样的事情:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> 

function loadData(){
    $('#table').load('yourScript.php',function (response, status, xhr) {
         // handle the response here and set the data
    });
}

loadData(); // This will run on page load
setInterval(function(){
    loadData(); // this will run after every 5 seconds
}, 5000);