homesupportsave into a local database via php + mysql [tutorial]

$link = mysql_connect($databasehost, $databaseuser, $databasepassword); //create connection to database

this section of code checks if the database name specified above already exists on your mysql server and if it doesn’t create it, along with a news articles table:

//if database doesn't exist create it
if(@mysql_select_db($databasename)==false){
$query = "create database $databasename";
if(!mysql_query($query))die("error in query: $query"); //exit script if database can't be created
//create a news articles table in the database
$query = "create table $databasename.`newsarticles` (
`id` int(10) unsigned not null,
`headline` varchar(255) not null,
`text` text not null,
`publisheddate` datetime not null,
`photourl` text null,
primary key (`id`))
engine=innodb default charset=latin1;";
if(!mysql_query($query))die("error in query: $query"); //exit script if table can't be created
mysql_select_db($databasename);
}

the final section of code is used to iterate through all the news items returned for your feed and save them into your database:

$feed = new apihandler($api_key, $baseurl); //create a new feed object using the api_key
$newslist = $feed->getnewshtml(); //return an array of the latest news items from your feed in html format

foreach($newslist as $news){
/* @var $news newsitem */

//prepare unsafe data for database
$headline = mysql_escape_string($news->getheadline());
$text = mysql_escape_string($news->gettext());
//process photo select default photo and return largeurl for it
$photos = $news->getphotos();
$photourl = mysql_escape_string($photos[0]->getlarge()->geturl());

//insert article into database, but ignore it if it already exists
$query = "insert ignore into newsarticles
values(".$news->getid().",'" . $headline ."','" . $text ."',
'" . $news->getpublishdate() . "','" . $photourl ."')";
if(!mysql_query($query))echo("error in query: $query");
}

mysql_close($link); //close database connection
echo "operation completed";

[jump to top]

[advanced example]

before you begin it is necessary to create a mysql databse with all the necessary tables and feeds you wish to record. please refer toadvanced database structure.

[using the php api to save into your newly created database]

below the script has been broken into several pieces in order to explain more easily. but should be copied into 1 script.

feed configuration

first setion of the code is used to configure your feed settings these are specifically your api_key and base url which are issued to you in your welcome pack. it is important to replace the example values given below with the details you’ve been given.




include_once 'samplefeedapi/apihandler.php';

$success = true; //initialise successful operation boolean
$api_key = "your_api_key"; //insert api key into this variable
$baseurl = "your_api_base_url"; //insert base into this variable

[jump to top]

database configuration

the next section requires you to configure your database settings as above the example settings need to replaced with values appropriate to your mysql configuration, the databasename however should remain the same unless you have modified this name in the initialadvanced database creation script.

//database configuration
$databasehost = "yoursqlserver";
$databaseuser = "root";
$databasepassword = "";
$databasename = "advancedsampledb";

$link = mysql_connect($databasehost, $databaseuser, $databasepassword);
mysql_select_db($databasename) or die("cannot find database");

[jump to top]

getting newsitems from your feed

the portion of code deals with returning an array of newsitems using the sample api. the apihandler class is instantiated using the api_key and baseurl values provided above, if the values are incorrect an exception will be thrown and the script will exit with a message detailing the exception.

$nilist = array();
try{
$feed = new apihandler($api_key, $baseurl); //create a new feed object using the api_key
$nilist = $feed->getnewshtml(); //return an array of the latest news items from your feed in html format
}
catch(exception $e){
die($e);
}

[jump to top]

processing each news item and preparing values for the database

each of the variables associated with a newsitem a prepared for the mysql query by escaping any special characters and making them safe for the query. we also intialise the updated and inserted counters to 0, which we use to track how many articles are updated and how many articles are inserted. we catch any exceptions thrown for each newsitem and skip the processing of that specific item as highligted in the catch block.

//initialize counters
$updated = 0;
$inserted = 0;

// process the news
foreach($nilist as $news){
/* @var $news newsitem */
try{
$encoding = mysql_real_escape_string($news->getencoding());
$headline = mysql_real_escape_string($news->getheadline());
$id = mysql_real_escape_string($news->getid());
$publishdate = mysql_real_escape_string($news->getpublishdate());
$createddate = mysql_real_escape_string($news->getcreateddate());
$lastmodifieddate = mysql_real_escape_string($news->getlastmodifieddate());
$extract = mysql_real_escape_string($news->getextract());
$text = mysql_real_escape_string($news->gettext());
$byline = mysql_real_escape_string($news->getbyline());
$source = mysql_real_escape_string($news->getsource());
$tweettext = mysql_real_escape_string($news->gettweettext());
$source = mysql_real_escape_string($news->getsource());
$state = mysql_real_escape_string($news->getstate());
$clientquote = mysql_real_escape_string($news->getclientquote());
$htmltitle = mysql_real_escape_string($news->gethtmltitle());
$htmlmetadescription = mysql_real_escape_string($news->gethtmlmetadescription());
$htmlmetakeywords = mysql_real_escape_string($news->gethtmlmetakeywords());
$htmlmetalanguage = mysql_real_escape_string($news->gethtmlmetalanguage());
$tags = mysql_real_escape_string($news->gettags());
$priority = is_int($news->getpriority())? $news->getpriority() : "null";
$format = mysql_real_escape_string($news->getformat());;

$categories = $news->getcategories();
$photos = $news->getphotos();
$comments = $news->getcomments();
}
catch (exception $e){
echo $e;
continue;
}

[jump to top]

update article operation

here a query is executed to check if a newsarticle already exists in the database with the fetched id, if it does then we process an update query inside the if block otherwise we skip the entire if block and go to the else block where we execute an insert query instead. if the query is successful the update counter is increased by 1.

//check if news article already exist in database if it does run an update query else insert query
$query = "select * from newsarticles where id = " . $id;
if(mysql_num_rows(mysql_query($query))){

$query = "update newsarticles
set headline = '" . $headline ."', extract = '" . $extract ."',
encoding = '" . $encoding ."', text = '" . $text ."', publishdate = '".$publishdate."',
byline = '" . $byline ."', tweettext = '" . $tweettext ."', source = '" . $source ."',
state = '" . $state ."', clientquote = '" . $clientquote ."',
createddate = '".$createddate."', lastmodifieddate ='".$lastmodifieddate."',
htmltitle = '" . $htmltitle ."', htmlmetadescription = '" . $htmlmetadescription ."',
htmlmetakeywords = '" . $htmlmetakeywords ."', htmlmetalangauge = '" . $htmlmetalanguage ."',
tags = '" . $tags."', priority = " . $priority ."
, format = '" . $format ."'
where id = $id ";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
else $updated++;

part of the update also involves deleting associated photos and comments for reasons of simplicity as they are re-added in later method calls. with respect to categories however, only the relationships with news articles are deleted, this as with the aformentioned is re-added in later method calls.

//check if photos already exist in database if they do delete them as they will be re-added in the initialisephotoquery method
$subquery = "(select newsphotoid from newsarticlephotos
where newsarticleid =". $id .")";
if(mysql_num_rows(mysql_query($subquery))){
$query = "delete from newsphotos
where id in ".$subquery;
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}

//delete all category relationships with this article as will be re-added in initialecategoryquery method
$query = "delete from newsarticlecategories
where newsarticleid =". $id;
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}

//delete all existing comments for this article as will be re-added in intiliasecommentsquery
$subquery = "(select newscommentid from newsarticlecomments
where newsarticleid =". $id .")";
if(mysql_num_rows(mysql_query($subquery))){
$query = "delete from newscomments
where id in ".$subquery;
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}
}

[jump to top]

processing each news item and preparing values for the database

if an article does not exist then this portion of code inside the else block will be processed, which is simply a mysql insert statement if successful the insert counter is increased by 1 if not the query is echoed to the page.

else
{
$query = "insert into newsarticles
values(".$id.",'" . $headline ."','" . $extract ."',
'" . $encoding ."','" . $text ."','".$publishdate."',
'" . $byline."','" . $tweettext ."','" . $source."',
'" . $state ."','" . $clientquote."','".$createddate."',
'".$lastmodifieddate."','" . $htmltitle."','" . $htmlmetadescription."',
'" . $htmlmetakeywords ."','" . $htmlmetalanguage ."','" . $tags."',
" . $priority .",'".$format."')";

if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
else $inserted++;
}

[jump to top]

processing each news item and preparing values for the database

the final operations inside the foreach loop apply to both updates and inserts and are calls to 3 methods which handle the processing of photos, categories and comments to the database, each method is discussed in more detail further down the page:

// perform the photo category and comments update to the database
initialisephotoquery($photos, $id);
initialisecategoryquery($categories, $id);
initialisecommentsquery($comments, $id);
}

[jump to top]

checking if operation was successful and closing database connection

this portion of code is used display the number of articles successfully updated and inserted and any errors if there were any:

if ($success)echo "operation completed successfully: $updated articles updated, $inserted articles inserted";
else echo "there was a problem saving all your news articles to the database, see errors above - $updated articles updated, $inserted articles inserted";
mysql_close($link);

[jump to top]

the photo processing method

this method is used to add all photo information associated with an article into the photos table and also establishes article and photo relationships in the relevant database table as well all variable values associated with a photo are safely escaped for the query as well.

//add photos and their relationships to news articles into database
function initialisephotoquery($photoarray, $id){
$query = "";
foreach ($photoarray as $photo){
/* @var $photo photo */
$alt = mysql_real_escape_string($photo->getalt());
$photoid = mysql_real_escape_string($photo->getid());

$largeurl = ($photo->getlarge()->geturl() != "null")?"'".mysql_real_escape_string($photo->getlarge()->geturl())."'":"null";
$largeheight = mysql_real_escape_string($photo->getlarge()->getheight());
$largewidth = mysql_real_escape_string($photo->getlarge()->getwidth());

$thumburl = ($photo->getthumb()->geturl()!= "null")?"'".mysql_real_escape_string($photo->getthumb()->geturl())."'":"null";
$thumbheight = mysql_real_escape_string($photo->getthumb()->getheight());
$thumbwidth = mysql_real_escape_string($photo->getthumb()->getwidth());

$hiresurl = ($photo->gethires()->geturl()!= "null")?"'".mysql_real_escape_string($photo->gethires()->geturl())."'":"null";
$hiresheight = mysql_real_escape_string($photo->gethires()->getheight());
$hireswidth = mysql_real_escape_string($photo->gethires()->getwidth());

$customurl = ($photo->getcustom()->geturl()!= "null")?"'".mysql_real_escape_string($photo->getcustom()->geturl())."'":"null";
$customheight = mysql_real_escape_string($photo->getcustom()->getheight());
$customwidth = mysql_real_escape_string($photo->getcustom()->getwidth());

$orientation = mysql_real_escape_string($photo->getorientation());

$query = "select id from newsphotos where id =" . $photoid;
if(!mysql_num_rows(mysql_query($query))){
$query = "insert into newsphotos values(".$photoid.",'" . $alt ."','" . $orientation ."',
" . $thumbwidth ."," . $thumbheight ."," . $thumburl . "," . $largewidth .",
" . $largeheight ."," . $largeurl . "," . $hireswidth . "," . $hiresheight . ",
" . $hiresurl . "," . $customwidth . "," . $customheight . "," . $customurl . ")";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}
$query = "insert into newsarticlephotos(newsarticleid, newsphotoid) values (" . $id . ",". $photoid . ")";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}
}

[jump to top]

the categories processing method

this method is used to add all category information associated with an article into the categories table, if it doesn’t already exist, furthermore it establishes article and category relationships in the relevant database table as well all variable values associated with a category are safely escaped for the query as well.

//add categories and their relationships to news articles into database
function initialisecategoryquery($categoryarray, $id){
$query = "";
foreach ($categoryarray as $cat){
/* @var $cat category */
$categoryid = mysql_real_escape_string($cat->getid());
$categoryname = mysql_real_escape_string($cat->getname());
$query = "select * from newscategories where id = " . $categoryid;
if(!mysql_num_rows(mysql_query($query))){
$query = "insert into newscategories values(".$categoryid.",'" . $categoryname ."')";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}
$query = "insert into newsarticlecategories(newsarticleid, newscategoryid) values (" . $id . ",". $categoryid . ")";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}
}

[jump to top]

the comments processing method

this method is used to add all comments information associated with an article into the comments table and also establishes article and comment relationships in the relevant database table as well. additionally all variable values associated with a comment are safely escaped for the query.

//add comments and their relationships to news articles into database
function initialisecommentsquery($commentsarray, $id){

foreach ($commentsarray as $comment){
/* @var $comment comment */

$commentid = mysql_real_escape_string($comment->getid());
$commentuser = mysql_real_escape_string($comment->getuser());
$commentpostdate = mysql_real_escape_string($comment->getpostdate());
$commentlocation = mysql_real_escape_string($comment->getlocation());

$query = "insert into newscomments values(".$commentid.",'" . $commentuser ."','".$commentpostdate."',
'" . $commentlocation ."')";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}

$query = "insert into newscomments(newsarticleid, newscommentid) values (" . $id . ",". $commentid . ")";
if(!mysql_query($query)){
global $success;
$success = false;
echo("incorrect query: " . $query . "

");
}
}
}
?>

[jump to top]