Jump to content

Putting data from XML into SQL using PHP


Popple3

Recommended Posts

Hi,

I wrote a quick script that *should* check my friends timeline on twitter and dump certain info into an SQL database.

The idea is that the script will check if a status exists in my SQL, and if it doesn't, add it, and send an SMS to me using a class my friend wrote (SMS isn't in the script yet, I just want SQL working first). I will then do a cron job on this to check from time to time.

 

Here is the code (without certain, obvious data):

 

<?php
//------CONNECT TO DATABASE-----
$db = mysql_connect("$sql_server", "$sql_user", "$sql_pass") 
    or die("Connection Failure to Database");
mysql_select_db("$sql_db",$db);
//------------------------------

//------GET FRIEND STATUSES-----
$ch = curl_init();
curl_setopt ($ch, CURLOPT_URL, 'http://user:[email protected]/statuses/friends_timeline.xml');
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
$xmldata = curl_exec($ch);
curl_close($ch);
//------------------------------

$xml = new SimpleXMLElement($xmldata); //parse friend statuses


function checkStatus($text) { //Check if status is in SQL database
$checksql = "SELECT * FROM tweets WHERE status='$text'";
$checkresult = mysql_query($checksql);
if ($checkresult) {
	return true;
} else {
	return false;
}
}

function insertStatus($id, $user, $text, $time) { //Insert status into database
$insertsql = "INSERT INTO tweets (id, user, status, time) VALUES ('$id', '$user', '$text', $time')";
$insertresult = mysql_query($insertsql);
}

//-----GO THROUGH EACH STATUS-----
foreach($xml->status as $status) {
$tweetid = $status->id;
$tweettime = $status->created_at;
$tweettext = $status->text;
$tweetuser = $status->user->screen_name;

$check = checkStatus($tweettext); //returns true or false
if ($check=false) {
	insertStatus($tweetid, $tweetuser, $tweettext, $tweettime); //inserts into SQL database
	echo $tweetuser.": ".$tweettext."\n";
}
}
//--------------------------------
?>

 

Any ideas why it's not working? I'm stumped!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.