user3038421
user3038421

Reputation: 25

php long polling using mysql

I found a script that uses php long polling. It uses the following code to see if the text file is changed and returns the content. This is received by the browser.

How can i change this to read a table and see if there are new events ?

$filename= dirname(__FILE__)."/data.txt";

$lastmodif = isset( $_GET['timestamp'])? $_GET['timestamp']: 0 ;
$currentmodif=filemtime($filename);


while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif =filemtime($filename);
} 

$response = array();
$response['msg'] =Date("h:i:s")." ".file_get_contents($filename);
$response['timestamp']= $currentmodif;
echo json_encode($response);

I have a table where there are 'posts'. post_id,content,user_id,posted_time

How can i know if theres a new post ?

Upvotes: 1

Views: 1451

Answers (1)

Kevin Goedecke
Kevin Goedecke

Reputation: 1983

You basically just have to fetch a new result, thats it, if you want to check if there are new results since the last execution of the script you have to save the output somewhere (is that what you want to do?)

See the following code, for a regular MySQL query:

<?php
// Connect to your MySQL DB
@$db = mysqli_connect("localhost", "root", "", "database");

// Check connection and echo if an error occurs
if (mysqli_connect_errno()) {
  printf("Connection failed: %s\n", mysqli_connect_error());
  exit();
}

// Execute SQL Query, replace this with your Query (maybe the one I put in fits for your needs)
$query = mysqli_query($db, "SELECT * FROM posts");

// Transform the result into an array if your you got new elements in the MySQL DB.
$resultat = mysqli_fetch_assoc($befehl);

// Close connection
mysqli_close($db);
?>

Upvotes: 1

Related Questions