Hello. Can someone explain how to create a .php page which auto-updates with values from a database? Would using AJAX be best for something like this? I want this PHP code, but I want the page to be updated whenever 'values01' is added to or changed, without having to refresh the page.
$query = "SELECT values01 FROM users WHERE username='$username'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
echo nl2br("{$row['values01']}");
}
Any help would be appreciated! :)
views:
36answers:
1
+2
A:
What you are describing would be a push notification from the web server. Unfortunately, I have not found a reliable way to do a traditional push, where the web server would initiate the connection with the client (from my limited research, it appears that there were proposals for the http standard to support push, however, it doesn't look like a widely adopted standard ever emerged). However, this can be done in a bit more roundabout way.
There is a way around the push limitation that is typically used:
- Browser connects to the page, loads up the current "state" of the database. A session variable (lets call it $_SESSION['currentState']) is saved with the starting state of the database. A javascript timer on the client's browser starts ticking down (lets just say that timer is 10 seconds long).
- Once the timer expires, an AJAX call is made to a script on the server. Lets call that script "updateValues.php". updateValues.php checks the new state of the database. If the database differs from $_SESSION['currentState'], we return whatever changes have been made, in some nice form (json, xml, etc..), and update $_SESSION['currentState'] with the new state. If there was no change, we reply with something to that extent.
- Upon receiving the data, the browser executes some javascript that then updates the rendering in the browser if changes have been made to the db, and then restarts the timer.
- goto 2.
The only thing you are missing here from a typical push notification, is the 10-second (or whatever you choose for your timer) lag.
MarkD
2010-07-26 16:01:38
what you said minus even worrying about push.
Talvi Watia
2010-07-27 13:35:16
@Talvi Watia: I wouldn't exactly say I was "worrying" about push.. just pointing out that the OP was describing a push-like system (with his required specs).
MarkD
2010-07-28 14:17:59