Home > Net >  reload my webiste one table only when database is updated || or reload table only 2 second to get ne
reload my webiste one table only when database is updated || or reload table only 2 second to get ne

Time:10-05

when the database in phpmyadmin get updated then i want to update the table values live to get new values from database.
so when the values are updated in database i can get new values.
i have done the below code it is working but thing is that the full web page will be reload after 2 second and data will be updated but i want to load data only not full webpage so please give me solution for this.

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<?php

require './connect.php';

$sql = "SELECT * FROM labours";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  echo "<div id='div1'><table border='2' width='100%' height='20%' style='text-align:center;font-size:50px; id='table'>
  <tr><th>ID</th><th>NAME</th><th>WORK</th><th>SALARY</th></tr>";
  while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . $row["id"]. "</td><td>" . $row["name"]. "</td><td>" . $row["work"]. "</td><td>". $row["salary"] . "</td></tr>";
  }
  echo "</table></div>";
} else {
  echo "0 results";
}
$conn->close();

?>

<script>
  setTimeout(function () 
  {
    window.location.reload(1);
  }, 2000);
</script>

CodePudding user response:

You have to seperate your code into two files

index.php:

<script src="https://code.jquery.com/jquery-3.5.0.js"></script>

<div id="results">
</div>

<script>
  setInterval(function ()
  {
    $.ajax({
      type: "GET",
      url: 'http://localhost/Stackoverflow/reload_data/get_data.php', // CHANGE THAT
      success: function(res){
        $('#results').html(res);
      },
      dataType:'html',
    });
  }, 2000);
</script>

get_data.php:

<?php

require './connect.php';

$sql = "SELECT * FROM labours";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
  // output data of each row
  echo "<div id='div1'><table border='2' width='100%' height='20%' style='text-align:center;font-size:50px; id='table'>
  <tr><th>ID</th><th>NAME</th><th>WORK</th><th>SALARY</th></tr>";
  while($row = $result->fetch_assoc()) {
    echo "<tr><td>" . $row["id"]. "</td><td>" . $row["name"]. "</td><td>" . $row["work"]. "</td><td>". $row["salary"] . "</td></tr>";
  }
  echo "</table></div>";
} else {
  echo "0 results";
}
$conn->close();

?>

I hope it helps.

  • Related