Articles

TUTORIALS

October 12 2010

Twitter Feed Application Tutorial

By Bill Krom

In: Tutorials - Leave a Comment

So I was looking over the Twitter API the other day, and I noticed they have officially switched their system to the Oauth protocol. All 3rd party applications now need to go through a complicated (while better) hand shake process before being granted access to account information. This is a giant leap forward for Twitter, but it may leave most average web developers scratching their heads, breaking things, and even slapping the keyboard around a bit and no one wants to see that!

I have written an application that will pull your twitter feed from twitter via access to your publicly available RSS feed, slide the data into your own database, and run quietly in the background all while remaining within the usage requirements set forth by Twitter.

I had no need to collect every bit of information from the BizLab Twitter account. I merely needed a way to display a "live" feed of recent tweets for the visitors to our website. In the anticipation of web designers and developers that will not be interested in creating complex applications that work with the new Oauth system, I integrated more functionality to allow the system to easily adapt to various needs.

This application will:


  1. Collect every tweet from a specified users account, via cURL access to the public RSS feed

  2. Fill the database with the number of records you set as the limit (default to 5)

  3. If the number of available tweets does not reach your set limit (eg: your Twitter account only has 1 of the 5 tweets you want on your page), the application will continue to fill in new tweets until they reach your set limit (5 in this example)

  4. If your limit has been reached, and you post a new tweet, the oldest tweet will be deleted and the latest one will be inserted into the database

  5. If a tweet has been deleted within twitter, the deletion will be replicated on your end. The empty database row will be filled with the most recent tweet not already in the system

  6. If you decide to raise or lower the number of records the system will automatically drop or insert the new fields into the database. There is no need to manually delete or add database records



This system can be arranged to run via CRON job (a server automated task) or via AJAX on page load. Either way, the data will be immediately available on page load, since the tweet data is pulled from your local database system and is not dependent on the reliability of the twitter system.

This application is written entirely in PHP and is intermediate to advanced in form, so if you are new to PHP, this tutorial is not a great place to start. JQuery is the library of choice, because it rocks. It is assumed that you have experience in and understand the other aspects of modern web programming including PHP, AJAX, database connections, cURL, HTML, or Javascript. A working version of the application is available here (7zip compressed file). The compressed file provides everything you need to get up and running, including a database setup text file. The code contains detailed commenting on a line by line basis, explaining the purpose and action of each line.

Download the entire code here (7zip compressed file): Twitter Feed Application

Now on to the goodies. As with any computer programming tutorial, the easy way out will never teach you how to improve your code and advance your skills as a developer – if you want to learn this, begin by typing out all the code by hand. There is no better way to learn to program than simply writing 1000’s of lines until you begin to understand how it works (of course nothing substitutes a great manual).

We begin with the base file Feed.php. Here, we will build the container that will hold your tweets as they are streamed to your web page. Animation is handled by JQuery. I will not go into details here, since this tutorial is not for HTML, but I will say that the "tw_feed_data" div HTML is a place holder until the Javascript begins to run. This HTML can be removed from the DIV and the program will work just fine.



<div id="twitter_feed">

<div id="tw_header">

<p><a href="http://www.twitter.com/bizlabweb" target="_blank">Follow BizLab On Twitter</a></p>


</div><!-- end of asset_header div -->

<div id="tw_content">

<div id="tw_feed_data">

<!-- AjAX tweet content -->


<!-- this content is replaced with the twitter feed -->

<div class="inner_tw_box">

<p>Content item 1</p>


</div>

<div class="inner_tw_box">

<p>Content item 1</p>

</div>

<div class="inner_tw_box">


<p>Content item 1</p>

</div>

<div class="inner_tw_box">

<p>Content item 1</p>


</div>

<div class="inner_tw_box">

<p>Content item 1</p>

</div>

</div><!-- end of tw_feed_data div -->


</div><!-- end of tw_content div -->

<div class="more"><p><a href="http://www.twitter.com/bizlabweb" target="_blank">Follow Us</a></p></div>


</div><!-- end of twitter_feed div -->



This next code snippet comes from the get-feed.php file in the functions folder. This is the code activated by the AJAX Javascript call on the feed.php page above. I have the Javascript set to run every 2000ms (2 minutes) since there is no severe urgency behind getting this information up to the second.

This code grabs the current tweets from the database, orders them, sticks the results into an array, and formats it as JSON data to be returned to a Javascript callback function. The only semi-fancy part of this code is the multi-dimensional array being built below. Don’t worry about that for now. I will have another tutorial on these soon.




<?php

require_once('../globals/appvars.php');

// initialize the array


$tweet_stack = array();

// get the current tweets

$query = "SELECT content, pub_date, DATE_FORMAT(pub_date, '%M %d at %l:%i%p') AS pd FROM tweets ORDER BY pub_date DESC";


$result = $db->query($query);

if($result->num_rows > 0){

while($row = $result->fetch_assoc()){

$content = htmlentities(stripslashes($row['content']));


$pub_date = $row['pd'];

// SEND THIS BACK AS JSON DATA

$new_tweet = array('content'=>$content, 'pub_date'=>$pub_date);


// push this item into the tweet_stack array

array_push($tweet_stack, $new_tweet);

}


// send JSON data back to the AJAX request

echo json_encode($tweet_stack);

}


else{

return false;

}

?>



Now we will begin writing the script that will perform the heavy lifting. This code is very involved and will test some of your limits on conditions. Conditional statements (sometimes mistakenly called "if else" statements) are the basis for intelligent programs. The deeper the levels of condition you apply to your code, the more your program will be able to do. Conditions are deceiving due to the amount of code involved. The thing to keep in mind here is that the only about half of the code is run in any given scenario - for instance, when something passes or fails a condition, but both cannot (hopefully) happen.

We will start by declaring the functions that control some of the repeated actions needed in the application like deleting old posts, inserting new ones, and anything else that will need to be done more than once. It is easy to OD on functions, so be sure to only use them in instances where it HELPS the end result of your code. You don't need to write functions for areas of code that aren't repeated, in my opinion.

Here is the orderTweets() function that will be used to arrange the records in the array from latest to oldest for our program. It basically changes the records position in the array forward or backward after comparing the post date of the two compared records.



function orderTweets($x, $y){

$x = strtotime($x['pub_date']);


$y = strtotime($y['pub_date']);

if($x==$y){

return 0;

}


else if($x<$y){

return 1;

}

else{

return -1;


}

}



This next function checkRecord() is used to see if the current record already exists in the database, if not the program will allow this new record to be inserted. If the current record is found in our system, the record will not be re-inserted. This is a basic return true or return false function, but you may notice the reference to the global $db variable here. When using variables that have been declared (in this case) on another script (appvars.php) you will need to re-declare them inside the function in this manner to allow them access to the goodies contained in the variable. This variable is the database connection.



function checkRecord($content, $pub_date){

global $db;

$query = "SELECT * FROM tweets WHERE content='$content' AND pub_date='$pub_date'";


$result = $db->query($query);

if($result->num_rows==0){

return false;

}


else{

return true;

}

}



This is the insertTweet function, used for... well you guessed it, Inserting new tweets into our database! It utilizes a basic MySql insert statement.



function insertTweet($content, $pub_date){

// the current tweet is not in the DB, so insert it now


global $db;

$query = "INSERT INTO tweets (content, pub_date) VALUES('$content','$pub_date')";


$db->query($query);

}



This function, deleteTweet(), is used to remove any unwanted records from the system. First, it finds the oldest date record. This method provides a high level of accuracy because we include the seconds in the timestamp of every tweet, and it is nearly impossible to submit 2 tweets with the exact same timestamp.



function deleteTweet(){

global $db;

// find the oldest tweet record


$query = "SELECT MIN(pub_date) AS pub_date FROM tweets";

$result = $db->query($query);


$row = $result->fetch_assoc();

$pub_date = $row['pub_date'];

// now delete this oldest tweet


$q2 = "DELETE FROM tweets WHERE pub_date='$pub_date' LIMIT 1";

$db->query($q2);


}



This next function, updateTweets(), will be used to update our system in the event of a record deletion on the Twitter end of the application (eg: if you delete a tweet from your twitter account). This function is a bit more complicated, but to summarize, we collect all the records in our database, compare them to the $tweet_stack array data (created when we request the data from twitter, and if there are any records in our system that are NOT in the $tweet_stack array, we remove and replace them with some new data from the $tweet_stack array.



function updateDB($tweet_stack){

// get the DB records


global $db;

$query = "SELECT content, pub_date FROM tweets ORDER BY pub_date DESC";


$results = $db->query($query);

while($row = $results->fetch_assoc()){

$current_pub_date = $row['pub_date'];


if(array_search($current_pub_date, $tweet_stack)===false){

// this tweet has been deleted on Twitter, delete it in the DB


$q2 = "DELETE FROM tweets WHERE pub_date='$current_pub_date' LIMIT 1";

$db->query($q2);


$i=0; // set the iterator for the foreach loop.

foreach($tweet_stack as $stack){

if($i>0){ break; }


$content = mysqli_real_escape_string($db, $stack['content']);

$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));


// check to see if this tweet has already been recorded

$existing = checkRecord($content, $pub_date);


// insert the newest tweet that isn't already in the DB 

if(!$existing){


insertTweet($content, $pub_date);

$i++;

}

}

}




}

}



Now that we have all of our functions, we will declare our variables. Try to keep any variables that will be used throughout your program at the top of the script for easy access when changes are needed.



// set your email address here 

$email = 'bill@bizlab.us';


// set this link to your personal twitter RSS feed

$url = 'http://twitter.com/statuses/user_timeline/172689882.rss';

// set your tweet record limit 


// if you change this number, you will need to modify both the CSS and Javascript controlling the scroll distance


$tweet_record_limit = 5;

// initialize the array

$tweet_stack = array();




Next we will perform the cURL which basically allows PHP to render a web page from another website. There are many different settings that are available when you use the cURL request method. This cURL grabs the Twitter accounts RSS feed information (your tweets) and dumps the data into the aptly named "data" variable.


// begin your cURL request

$tw = curl_init();


curl_setopt($tw, CURLOPT_URL, $url);

curl_setopt($tw, CURLOPT_HEADER, false); // turns off HTTP headers with output

curl_setopt($tw, CURLOPT_RETURNTRANSFER, TRUE);


$data = curl_exec($tw);

curl_close($tw);




Now that we have attempted a request for data from the Twitter account, we are able to check the contents of the $data variable to look for certain key phrases returned by Twitter in the event that the request has failed or is empty. When using the PHP function you MUST check for existing strings using the === is exactly equal to operator.



if((strpos($data_string,'over capacity')===false)

&&(strpos($data_string, 'rate limit exceeded')===false)


&&(!empty($data_string))){



Something important to mention is the order in which you write your conditional statements. This workflow works well with any regular high-level (C++, Java, PHP, Javascript, ect) programming language. Try to structure your conditions to result in a true statement, meaning that if you are looking for (and expect) data in the $data variable you will not write the initial condition as if(!$data){ do stuff ; }. Instead you will write a true condition as the initial "if" (eg: if($data){ now we’re talking; } ). In large scale applications, you will see an increase in performance of your programs.

For conditionals, write the true (or expected majority result condition) first, close the code block with your closing brace, and then immediately write your alternate conditions using this structure:



if($my_var==50){

// true or majority result

}


else{

// on failure, or alternate condition

}



After you have your basic code framework written out, you can begin to fill in the details about what exactly will be happening in this block of code. This will help you keep track of complex nested conditional statements like you will see in a moment.

That in mind, I will be walking through this tutorial in a progressive manner, opposed to the logical manner you would want to write you own application code. In the next section of code we will pull the RSS data out of the $data variable, run it through the SimpleXMLElement operation, and place the data into a variable named $tweets.

This part of code loops through each item that has been retrieved and pulls out the information we need to make our twitter feed. Here, I will pull the pub_date and content of the record, trim the content, and place it into the $tweet_stack array. This now gives us a streamlined, multi-dimensional array to work with. By using this method, I am able to "clean" the data and remove the things we don’t need.



// begin manipulating the ATOM FEED

$tweets = new SimpleXMLElement($data);


// loop through the array to get the tweets

foreach($tweets->channel->item as $tweet){


$published = $tweet->pubDate; // RSS DATE FORMAT: Thu, 05 Aug 2010 11:24:35 +0000 


$content = trim($tweet->description);

// push data into an array

$new_tweet = array('content'=>$content, 'pub_date'=>$published);


array_push($tweet_stack, $new_tweet);

}



This next block of code will sort the array from latest to oldest, placing all the records in the order we will want for processing. After the sorting, we find the latest tweet data by collecting the data in the first index of the array. Don’t forget to convert the RSS date to a MySQL friendly date format for storage in the DB. Collect the total number of tweets and use this information to set the $limit variable, which will tell the script how many times (or how many more times) to allow it to run. Keeping your program from running unnecessary iterations is really important when writing complex or large applications.



// sort the array in DESC order to allow the most recent tweets to be first


usort($tweet_stack, 'orderTweets');

// find the latest tweet

$latest_tweet = mysqli_real_escape_string($db, $tweet_stack[0]['content']);


// convert the date to mysql Datetime format

$latest_date = date("Y-m-d H:i:s",strtotime($tweet_stack[0]['pub_date']));


// find the total number of tweets

$num_tweets = count($tweet_stack);

// set the limit for the number of tweet records to record - change with the $tweet_record_limit var above


($num_tweets > $tweet_record_limit ? $limit = $tweet_record_limit : $limit = $num_tweets);



This next code block is rather lengthy, but it performs a few conditional checks. We first search for existing tweets. This means that we are looking for whether the Twitter account you have connected your application to has any tweets in it or not. If it does, we enter this "majority true" condition. Once inside the condition, we will search our database for the most recently recorded tweet.

This next condition determines the action of the program. If you currently have less records in your database than you wanted for your system (eg: your Twitter account only had 4 of the 5 tweets you were looking for) it will enter this condition. Once here, we will set the $i iteration counter variable to the number of existing rows in the database. You can think of this as starting your insertion actions where you left off (for this example, beginning the iteration counter at 4 since you currently have 4 records in the system).

We will then loop through the $tweet_stack array inserting each new (unique) record until we reach the $limit. At that point, the break; condition will stop the foreach() loop. This prevents the program from running unnecessarily. Remember also that we are not just inserting any old record into our database, we need the record to be NEW to prevent duplicate insertions.



// search for existing records in the DB

$query = "SELECT pub_date FROM tweets";


$result = $db->query($query);

$row_count = $result->num_rows;

// if you have existing tweets


if(($row_count > 0)&&($row_count <= $limit)){

// find the most recently recorded tweet

$q4 = "SELECT MAX(pub_date) AS pub_date FROM tweets";


$r4 = $db->query($q4);

$row = $r4->fetch_assoc();

$latest_record = strtotime($row['pub_date']);


// if you have less records in the DB than you need for your application, add more records


if($row_count < $limit){

$i=$row_count; // load the iteration count with the number of existing rows


foreach($tweet_stack as $stack){

// grab the current tweet from the array

$content = mysqli_real_escape_string($db, $stack['content']);


$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));

// check to see if this tweet has already been recorded


$existing = checkRecord($content, $pub_date);

if(!$existing){

insertTweet($content, $pub_date);// insert the new one


$i++; // increment the counter, ONLY if this is a new tweet

}


// stop the loop at the user defined limit

if($i==$limit){ break; } 

}


updateDB($tweet_stack); // compare the DB data with the FEED to see if any Tweets have been deleted


}



The next two conditions will run if your program has already reached the $limit. In this case, we will first examine the $tweet_stack array to see if any of the tweets are more recent than the most recent record in the database, and if so, update your database. This section will continue to loop through the $tweet_stack until it runs out of new tweet data to be inserted. Remember that before you can add your new records to the DB you will need to remove the oldest tweet records. Once they are removed, you can insert the new records at will.

We will run the updateDB() function in order to clear any Twitter deleted tweets that still remain in our system. If there were no new tweets, our program will still check for anything that may have been deleted since the last time it was run.



// your table has reached the record limit, now see if there are any new tweets


else if(strtotime($latest_date) > $latest_record){

foreach($tweet_stack as $stack){

// grab the current tweet from the array


$content = mysqli_real_escape_string($db, $stack['content']);

$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));


if(strtotime($pub_date) > $latest_record){

mail($email,'BizLab CRON Successful','The cron job has run successfully');


echo '<p>Deleting old tweets...</p>';

deleteTweet(); // this is a new tweet, now find the oldest tweet and delete it


echo '<p>Putting the new tweets...</p>';

insertTweet($content,$pub_date); // insert the new one


}

}

updateDB($tweet_stack);

}

else{

updateDB($tweet_stack);


}

}



This next code block is purely for database maintenance. If you decide to change the $limit for your application to 10 records, and happen to change your mind in the future and lower it back to 7, this condition will trim off the extra records to reduce your database back to the desired size.



// if you have more records in the DB than you want, remove each one over the limit
else if($row_count > $limit){
// delete the extra records beginning with the oldest
$extras = $row_count - $limit;
while($extras > 0){
// find the oldest tweet and delete it
deleteTweet();
$extras--;
}
updateDB($tweet_stack);
}



This last condition (least probably condition) is run when you run the application for the first time. This will attempt to fill your database.




else{

// build the initial table

$i=0;


foreach($tweet_stack as $stack){

// grab the tweet data from the array and organize it for insertion into the DB


$content = mysqli_real_escape_string($db, $stack['content']);

$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));


// insert the new one

insertTweet($content, $pub_date);

$i++;

// stop the loop at the user defined limit


if($i==$limit){ break; } 

}

}

}



So at this point you may be saying, "is this guy crazy?!? All this code for a simple Twitter feed? There must be an easier way to do it!". Unfortunately, this is the easier way =^P

You can build a more bare bones application that will do the job, but this was written to handle every condition I can think of when working with Twitter feeds, all while avoiding the Oauth process. I recommend using a CRON process every 5 minutes or so to avoid overloading Twitter and remain inside their recommended 1 call per minute. Most people will not need such frequent updates for their feed.

I also recommend using Javascript to call the get-feed.php page every 30 seconds to 2 minutes. Each time you call the get-feed.php script, it will send an AJAX request to the database, pull out any new data, and update the tweet records displayed on your web page, all without having to reload the page. Of course, this script (get-feed.php) can also be turned into a PHP function and called each time the page loads. This method is good, especially if you are not fond of or knowledgeable in Javascript. Simply wrap the get-feed.php code in a function tag – something like function getFeed() will work perfectly, include the function on your page somehow, and call the function on your feed.php page (or where ever the feed will be displayed) - like so: getFeed();

Here is the entire twitter-cron.php script




<?php

/*

// ERROR REPORTING TURNED ON




ini_set("display_startup_errors", "1");

ini_set("display_errors", "1");

error_reporting(E_ALL);

*/


require_once($_SERVER['DOCUMENT_ROOT'].'/globals/appvars.php');



function orderTweets($x, $y){

$x = strtotime($x['pub_date']);


$y = strtotime($y['pub_date']);

if($x==$y){

return 0;

}


else if($x<$y){

return 1;

}

else{

return -1;


}

}

function checkRecord($content, $pub_date){

global $db;

$query = "SELECT * FROM tweets WHERE content='$content' AND pub_date='$pub_date'";


$result = $db->query($query);

if($result->num_rows==0){

return false;

}


else{

return true;

}

}

function insertTweet($content, $pub_date){

// the current tweet is not in the DB, so insert it now


global $db;

$query = "INSERT INTO tweets (content, pub_date) VALUES('$content','$pub_date')";


$db->query($query);

}

function deleteTweet(){

global $db;

$query = "SELECT MIN(pub_date) AS pub_date FROM tweets";


$result = $db->query($query);

$row = $result->fetch_assoc();

$pub_date = $row['pub_date'];


// now delete this oldest tweet

$q2 = "DELETE FROM tweets WHERE pub_date='$pub_date' LIMIT 1";


$db->query($q2);

}

function updateDB($tweet_stack){

// get the DB records

global $db;


$query = "SELECT content, pub_date FROM tweets ORDER BY pub_date DESC";

$results = $db->query($query);


while($row = $results->fetch_assoc()){

$current_pub_date = $row['pub_date'];

if(array_search($current_pub_date, $tweet_stack)===false){


// this tweet has been deleted on Twitter, delete it in the DB

$q2 = "DELETE FROM tweets WHERE pub_date='$current_pub_date' LIMIT 1";


$db->query($q2);

$i=0; // set the iterator for the foreach loop.

foreach($tweet_stack as $stack){


if($i>0){ break; }

$content = mysqli_real_escape_string($db, $stack['content']);

$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));


// check to see if this tweet has already been recorded

$existing = checkRecord($content, $pub_date);


// insert the newest tweet that isn't already in the DB 

if(!$existing){


insertTweet($content, $pub_date);

$i++;

}

}

}




}

}

// set your email address here 

$email = 'bill@bizlab.us';


// set this link to your personal twitter RSS feed

$url = 'http://twitter.com/statuses/user_timeline/172689882.rss';

// set your tweet record limit 


// if you change this number, you will need to modify both the CSS and Javascript controlling the scroll distance


$tweet_record_limit = 5;

// initialize the array

$tweet_stack = array();

// begin your cURL request


$tw = curl_init();

curl_setopt($tw, CURLOPT_URL, $url);

curl_setopt($tw, CURLOPT_HEADER, false); // turns off HTTP headers with output


curl_setopt($tw, CURLOPT_RETURNTRANSFER, TRUE);

$data = curl_exec($tw);

curl_close($tw);



$data_string = strtolower($data); // check to be sure there were no errors




if((strpos($data_string,'over capacity')===false)

&&(strpos($data_string, 'rate limit exceeded')===false)

&&(!empty($data_string))){

// begin manipulating the ATOM FEED


$tweets = new SimpleXMLElement($data);

// loop through the array to get the tweets


foreach($tweets->channel->item as $tweet){

$published = $tweet->pubDate; // RSS DATE FORMAT: Thu, 05 Aug 2010 11:24:35 +0000 


$content = trim($tweet->description);

// push data into an array

$new_tweet = array('content'=>$content, 'pub_date'=>$published);


array_push($tweet_stack, $new_tweet);

}

// sort the array in DESC order to allow the most recent tweets to be first


usort($tweet_stack, 'orderTweets');

// find the latest tweet

$latest_tweet = mysqli_real_escape_string($db, $tweet_stack[0]['content']);


// convert the date to mysql Datetime format

$latest_date = date("Y-m-d H:i:s",strtotime($tweet_stack[0]['pub_date']));


// find the total number of tweets

$num_tweets = count($tweet_stack);

// set the limit for the number of tweet records to record - change with the $tweet_record_limit var above


($num_tweets > $tweet_record_limit ? $limit = $tweet_record_limit : $limit = $num_tweets);

// search for existing records in the DB


$query = "SELECT pub_date FROM tweets";

$result = $db->query($query);

$row_count = $result->num_rows;


// if you have existing tweets

if(($row_count > 0)&&($row_count <= $limit)){

// find the most recently recorded tweet


$q4 = "SELECT MAX(pub_date) AS pub_date FROM tweets";

$r4 = $db->query($q4);


$row = $r4->fetch_assoc();

$latest_record = strtotime($row['pub_date']);

// if you have less records in the DB than you need for your application, add more records


if($row_count < $limit){

$i=$row_count; // load the iteration count with the number of existing rows


foreach($tweet_stack as $stack){

// grab the current tweet from the array

$content = mysqli_real_escape_string($db, $stack['content']);


$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));

// check to see if this tweet has already been recorded


$existing = checkRecord($content, $pub_date);

if(!$existing){

insertTweet($content, $pub_date);// insert the new one


$i++; // increment the counter, ONLY if this is a new tweet

}


// stop the loop at the user defined limit

if($i==$limit){ break; } 

}


updateDB($tweet_stack); // compare the DB data with the FEED to see if any Tweets have been deleted


}

// your table has reached the record limit, now see if there are any new tweets


else if(strtotime($latest_date) > $latest_record){

foreach($tweet_stack as $stack){

// grab the current tweet from the array


$content = mysqli_real_escape_string($db, $stack['content']);

$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));


if(strtotime($pub_date) > $latest_record){

mail($email,'BizLab CRON Successful','The cron job has run successfully');


echo '<p>Deleting old tweets...</p>';

deleteTweet(); // this is a new tweet, now find the oldest tweet and delete it


echo '<p>Putting the new tweets...</p>';

insertTweet($content,$pub_date); // insert the new one


}

}

updateDB($tweet_stack);

}

else{

updateDB($tweet_stack);


}

}

// if you have more records in the DB than you want, remove each one over the limit


else if($row_count > $limit){

// delete the extra records beginning with the oldest

$extras = $row_count - $limit;


while($extras > 0){

// find the oldest tweet and delete it

deleteTweet();


$extras--;

}

updateDB($tweet_stack);

}

else{

// build the initial table


$i=0;

foreach($tweet_stack as $stack){

// grab the tweet data from the array and organize it for insertion into the DB


$content = mysqli_real_escape_string($db, $stack['content']);

$pub_date = date("Y-m-d H:i:s",strtotime($stack['pub_date']));


// insert the new one

insertTweet($content, $pub_date);

$i++;

// stop the loop at the user defined limit


if($i==$limit){ break; } 

}

}

}

?>



Have fun and happy coding to you all. Feel free to leave some comments below, and please show some love by leaving my author comments in the code!

0 comments for "Twitter Feed Application Tutorial"

Leave a Comment