The Long Poll


Loading ....
 
There’s many methods of providing instant dynamic updates to your page, and Long Polling is always an option when you want your scripts to wait for something to happen remotely.

Essentially you’re putting your script into a loop which checks the state of some particular event.

For instance I may be waiting for a user to update a database field, and as soon as he does my conditional check inside that loop becomes valid, and an instruction is sent to break the loop, put the new data on my screen (or return it in some other way) and possibly restart the loop, waiting for the next update.

Not quite a REST-API, but a long-poll can be convenient and quick to achieve.

WITH PHP

The code will get the current contents of a database into a variable, and then start an open loop which checks the state of that variable. We use the ‘&’ placeholder in the variable check; this preserves the previous value of that variable as well as the current state. In this manner we can check the two for differences.

If there IS a change in the database then the logic breaks the script and gives me a simple on-screen update.

I want to get a list of guitar manufacturers from my database.  Each time a new brand is listed there, I want my PHP to tell me about it.

First then I’ll be using a connector to link to my database

connect.php
<?php

$db = new PDO("mysql:host=localhost;dbname=GuitarShop", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
var_dump($db) ;

?>

We’ll include the connect.php at the top of the runtime script.  Note I’m also using the set_time_limit() function.  If I don’t then my while loop will stop after 180 seconds, the default timeout period for a PHP script.

Note: Hope it helps that I commented my code for you.

longPoll.php
<?php

include 'connect.php' ;
set_time_limit(0);
function getData() {

// WE'LL DECLARE $db AS A GLOBAL VARIABLE SO THAT IT'S AVAILABLE OUTSIDE OF THIS FUNCTION
    global $db ;

// NOW WE SET UP A PREPARE STATEMENT AND SEND IT TO THE DATABASE CONNECTOR
    $query = $db->prepare("SELECT maker_name FROM makers;");
    $query->execute();
    $brands = $query->fetchAll(PDO::FETCH_COLUMN, 0);
    return $brands ;
}

$result = getData() ;

// WE'VE NOW GOT AN ARRAY CALLED RESULT WHICH CONTAINS OUR CURRENT LIST.  LET'S JUST PUT A COUNT OF THAT INTO A VARIABLE WE CAN USE AS A COMPARISON

$currentEntries = count($result) ;

echo "There are " . $currentEntries . " brands <br>" ;

// NOW WE'LL WRITE A NEVER ENDING LOOP WHICH CONTAINS A CONDITIONAL-CHECK ASKING IF THE DATABASE CONTAINS MORE ENTRIES THAN IT DID WHEN WE STARTED THE SCRIPT.

while(1) {

    if(dbIsChanged($currentEntries)) {
        echo json_encode("DB UPDATED - we now have $currentEntries          brands") ;
        break ;
    }

   sleep(3) ;
}

// THIS IS THE FUNCTION CALLED TO MAKE THE CHECK.  NOTE &$currentEntries IS A REFERENCE VARIABLE - IT REFERS TO THE VARIABLE WE ALREADY DECLARED RATHER THAT MAKE A CLONE OF IT, SO IF WE CHANGE THE VARIABLE INSIDE THIS FUNCTION IT'LL BE CHANGED OUTSIDE OF IT TOO. 
function dbIsChanged(&$currentEntries) {

    $manager = getData() ;
    $checkList = $manager ;
    $newRows = count($checkList) ;
    if($currentEntries != $newRows) {
        $currentEntries = $newRows ;
        return true ;
    } else {
        return false ;
    }
}
header('refresh:0') ;
?>

Script works great – everytime you add or delete something from the database the script kicks in, reports it, breaks the loop, starts again (thanks to the header(‘refresh’).

Using jQuery with AJAX

Of course the biggest drawback to long polling with PHP is that ALL the work is being done by YOUR backend.  Dammit, we’re giving power away, guys!

Far better to do this kind of thing using AJAX to remotely call your script to check the database periodically.  We’ll look at that in a different post.

Share and enjoy.
 


RELATED PRODUCTS
  • A Guide For Boot Camp Trainers To Take Their Boot Camps To The Higher Level
  • How to keep a woman attracted and faithful in a long distance relationship.
  • Discover Powerful Secrets To Give Women Mind-blowing Orgasmic Pleasure.
  • Acclaimed relationship expert system that brings long distance relationship together.
  • The Only Canned Meat In America Labeled For Long Term Food Storage
  • This is how to lose 2-3 pounds a week while enjoying whatever you want all weekend long.
  • Provides A Step-By-Step Ways To Inspire Your Man To Commit To You Without Ultimatums
  • Discover thousands of profitable, targeted keywords and calculate Keyword Competitiveness.
  • How to chemically control his mind with the secret 8 step method.
  • Clickbank Ads
     
    Share

    You may also like...

    Leave a Reply

    Your email address will not be published. Required fields are marked *