Reputation:
I have created a website which retrieves text which has been uploaded to my database. the problem with this is i want a refresh of the content from that database ever second. but i can't find how to do this anywhere. i want this done in the background. and if possible a way to make the textbook that i will put in later to input the data into the server, also not do a full refresh but send the content in the background. thank you every answer will count.
<?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 id, firstname, lastname FROM MyGuests ORDER BY id ASC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div id='message'> <br> ". $row["firstname"]. " " . $row["lastname"] . "<br> </div>";
}
} else {
echo "0 results";
}
$conn->close();
?>
Upvotes: 2
Views: 1073
Reputation: 5071
In a file, simply echo out the results. Then in another file, load the echoed results in a div like this:
db_results.php
file which will echo out results:
<?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 id, firstname, lastname FROM MyGuests ORDER BY id ASC LIMIT 10";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<p>". $row["firstname"]. " " . $row["lastname"] . "</p>";
}
} else {
echo "0 results";
}
$conn->close();
?>
display.php
file which will refresh the results in a div:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
setInterval(function() {
$("#load_results").load("db_results.php");
}, 1000);
});
</script>
</head>
<body>
<div id = "load_results"></div>
</body>
</html>
db_results.php
file will query database, will fetch the results and will echo them out. The second file (display.php
) loads the first file in a div and refreshes the div every second, so updated results are loaded in the concerned div.
P.S.: Keep both files in same directory or adjust the path accordingly.
Upvotes: 1