The code:
#!/usr/bin/php
<?php
error_reporting(E_ALL);
while(true){
// Check how many API calls remain
$rate_limit = json_decode(file_get_contents('http://api.twitter.com/1/account/rate_limit_status.json'),true);
// Array containing all the Twitter handles
$handles = array('le4ky');
if($rate_limit['remaining_hits']<count($handles)){
file_put_contents('tweet_gremlin.log', date('r') . ' Rate limit reached');
sleep(30);
}else{
// Establish the database connection
if(!$mysqli = mysqli_connect('localhost','twitterd','password','twitterd')){
die('Cannot connect to database');
file_put_contents('tweet_gremlin.log', date('r') . ' Cannot connect to the database');
}
// This is the big one. Loop through the $handles values, make an API call, and insert the tweets.
foreach($handles as $value){
// Get the handle's timeline and put it into $user_data
$user_data = json_decode(file_get_contents('http://search.twitter.com/search.json?q=from:' . $value . '&rpp=100'),true);
// Put only the results index (tweets) into into $user_data
$user_data = $user_data['results'];
for($i=0;$i<count($user_data);$i++){
// Lazy method for sanitizing variables
$id = mysqli_real_escape_string($mysqli,$user_data[$i]['id']);
$created_at = mysqli_real_escape_string($mysqli,$user_data[$i]['created_at']);
$from_user_id = mysqli_real_escape_string($mysqli,$user_data[$i]['from_user_id']);
$profile_image_url = mysqli_real_escape_string($mysqli,$user_data[$i]['profile_image_url']);
$from_user = mysqli_real_escape_string($mysqli,$user_data[$i]['from_user']);
$from_user_name = mysqli_real_escape_string($mysqli,$user_data[$i]['from_user_name']);
$text = mysqli_real_escape_string($mysqli,$user_data[$i]['text']);
$insert_tweets = "INSERT INTO tweets ('id','created_at','from_user_id','profile_image','from_user','from_user_name',`text`) VALUES ({$id},{$created_at},{$from_user_id},{$profile_image_url},{$from_user},{$from_user_name},{$text});";
$result = mysqli_query($mysqli,$insert_tweets);
}
}
sleep(30);
}
}
?>
This is basically just meant to be a “daemon” of sorts that retrieves data and inserts it into the database. For the life of me, I can’t figure out why the data isn’t being inserted into the database. The twitterd user has select and insert permissions on the database and can connect from any host.
You need quotes around string values in your SQL query:
I added them to all values, you can remove them on values you know are numeric (and validated with
intval(),floatval()or some other numeric validation function).I also replaced single quotes with backticks in your column names.