How can I refresh a page when a database is updated?
This is how I recently implemented a solution using jQuery.
PHP increments a field in the database every time a significant update occurs.
<?php
// Call this function when data changes
function update_clients()
{
mysql_query( "UPDATE pageGen SET id = id + 1 LIMIT 1" );
}
// Call this function to get the ID to pass to JavaScript
function get_update()
{
$result = mysql_query( "SELECT id FROM pageGen LIMIT 1" );
$update = mysql_result( $result, 0, 'id' );
return $update;
}
?>
When the page is initially loaded, populate a JavaScript variable with a number from the database:
<script type="text/javascript">
var pageGenID = 25218603 // generated by PHP
var processUpdate = function( response )
{
if ( pageGenID < response )
{
replace_current_data_with_new_via_ajax();
pageGenID = response;
}
}
// Compare our Page Generate ID against that of the server
var checkUpdates = function()
{
serverPoll = setInterval( function()
{
$.get('script_to_return_latest_pageGenID.php',
{ lastupdate: 1 },
processUpdate, 'html');
}, 10000 )
};
// Check for updates every 10 seconds
$( document ).ready( checkUpdates );
</script>
Refresh page if there is change in database
I have tested this by creating two files(autorefresh.php,index.php) and test db with table and it is working for me. I think the below code would be helpful, If not please share you code, i will check and fix it.
autorefresh.php
// Create connection
$db = new mysqli("localhost", "root", "","test");
$orderId = $_POST["orderId"];
$query = "SELECT * FROM orderinhomeonlinecall WHERE orderId='$orderId'";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_array($result))
{
$orderStatus = $row['orderStatus'];
$data = array(
'orderStatus' => $orderStatus
);
echo json_encode($data);
}
?>
index.php
<?php
$orderStatus ='pending';
$orderId =1;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var predefined_val = '<?php echo $orderStatus; ?>';// your predefined value.
$(document).ready(function () {
setInterval(function () {
$.ajax({
type: "POST",
url: "autorefresh.php", //put relative url here, script which will return php
data: {orderId: <?php echo $orderId; ?>}, // if any you would like to post any data
dataType: "json",
success: function (response) {
var data = response; // response data from your php script
if (predefined_val !== data.orderStatus) {
window.location.href = window.location.href;
}
}
});
}, 5000);// function will run every 5 seconds
});
</script>
Refreshing page after sql update
I managed to get the desired result by adding header('Location: ./editprofile.php');
after the database was updated. See bellow:
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
}
After:
if($title!=''){
$sql = "UPDATE users SET title=:title WHERE id=:id";
$stmt = $conn->prepare($sql);
if($stmt == false){
$error = "User Title update failed. Please try again.";
}
$result = $stmt->execute(array(":title"=>$title, ":id"=>$id));
if($result == false) {
$error = "User Title update failed. Please try again.";
}
$count = $stmt->rowCount();
header('Location: ./editprofile.php');
}
Automatically refresh the web page after updating the database
use mysql_affected_rows() function it returns the number of affected rows on success in case of insert,update and delete and -1 on failure.
check if condition is success use setTimeout(function(){location.reload();}, 500); to refresh the page automatically.
Reload Page with Javascript after Database changes
The easiest way (which has already been mentioned) would be to reload the page every x seconds.
This means however, that if the user is browsing / editing anything on the page, he only has x seconds to finish this before all the progress is lost.
You could use AJAX to check the database for changes however:
- Make a DB-Check.php script that outputs the latest database entry
- In your main file, include an AJAX script which pulls the
DB-Check.php every 30 seconds - Put the output from the DB-check.php in a new JS variable
- If the new variable is different from the old variable, refresh
the whole page (Or use AJAX to load the rest of the database)
Related Topics
Bubble Sort Implementation in PHP
Warning: Array_Combine(): Both Parameters Should Have an Equal Number of Elements
Sort Multidimensional Array by Date Column, Then Use Other Column Values If Dates Are the Same
Flip Associative Array and Store New Values in Subarrays to Prevent Losing Duplicated Values
Update Command-Line Output, I.E. for Progress
Facebook Error 'Error Validating Verification Code'
How to Create and Store Md5 Passwords in MySQL
How to Convert Excel Xls to CSV Using PHP
Pdo SQLite Could Not Find Driver... PHP File Not Processing
Belongstomany Relationship in Laravel Across Multiple Databases
$_Post Is Empty After Form Submit
Mod_Rewrite, PHP and the .Htaccess File
Php: $_Get and $_Post in Functions
How the Usort() Sorting Algorithm Works
PHP Tree Structure for Categories and Sub Categories Without Looping a Query