Jump to content

If string contains #mudder Add to the database


runnerjp

Recommended Posts

Hello all,

 

I am able to pull the last 4 tweets made by a user and add them to a database but I only want to add the last 4 tweets that have '#mudder' in.

 

this is what I have so far

 

MyTimeLine.php

<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class MyTimeLine {
/**
 * myTimeline PHP Script
 * This script gets a user's twitter timeline and returns it as a multidimension array
 * each array containing 'tweet, date and link' respectively.
 *
 * @author Opeyemi Obembe <ray@devedgelabs.com>
 * @copyright Copyright (c) 2010, devEdgeLabs.
 */

	var $count;
	var $feedUrl;
	var $username;
	
	//@params: twitter username, number of needed updates (20 max)
	function myTimeline($username, $count = 20)
	{
		$this->feedUrl = 'http://api.twitter.com/1/statuses/user_timeline/'.$username.'.rss';
		$this->count = $count > 20 ? 20 : $count;
		$this->username = $username;
	}
	
	function since($date)
	{
		$timestamp = strtotime($date);
		$seconds = time() - $timestamp;
		
		$units = array(
			'second' => 1,
			'minute' => 60,
			'hour' 	 => 3600,
			'day'	 => 86400,
			'month'  => 2629743,
			'year'   => 31556926
		);
		
		foreach($units as $k => $v)
		{
			if($seconds >= $v)
			{
				$results = floor($seconds/$v);
				if($k == 'day' | $k == 'month' | $k == 'year')
					$timeago = date('D, d M, Y h:ia', $timestamp);
				else
					$timeago = ($results >= 2) ? 'about '.$results.' '.$k.'s ago' : 'about '.$results.' '.$k.' ago';
			}
		}
		
		return $timeago;
	}
	
	// Returns a multidimentional array, each containg 'tweet, date and link' respectively
	function get()
	{
		// Append the count
		$url = $this->feedUrl;
		$url .= $this->count == 20 ? '' : '?count='.$this->count;
		
		// The http CURL thingy
		$curl_handle = curl_init();
		curl_setopt($curl_handle, CURLOPT_URL, $url);
		curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
		curl_setopt($curl_handle, CURLOPT_TIMEOUT, 10);//10 secs max
		$data = curl_exec($curl_handle);
		curl_close($curl_handle);

		// Some error? Return an empty array
		// You may want to extend this to know the exact error
		// echo curl_error($curl_handle);
		// or know the http status
		// echo curl_getinfo($curl_handle, CURLINFO_HTTP_CODE);
		if(!$data)	return array();
		
		// Some reformatting
		$pattern = array(
			'/[^(:\/\/)](www\.[^ \n\r]+)/',
			'/(https?:\/\/[^ \n\r]+)/',
			'/@(\w+)/',
			'/^'.$this->username.':\s*/i'
		);
		$replace = array(
			'<a href="http://$1" rel="nofollow">$1</a>',
			'<a href="$1" rel="nofollow">$1</a>',
			'<a href="http://twitter.com/$1" rel="nofollow">@$1</a>'.
			''
		);
		
		$tweets = array();
		$xml = new SimpleXMLElement($data);
		foreach($xml->children()->children() as $item)
		{
			$tweet = preg_replace($pattern, $replace, $item->description);
			$date = $this->since($item->pubDate);
			$permalink = $item->link;
			$tweets[] = array($tweet, $date, $permalink);
		}
		
		return $tweets;
	}
}
?>

index.php

$db_values = '';
$tweet_feeds = '';

$min = 0;
$to_time = strtotime(date("Y-m-d H:i:s"));
$from_time = strtotime($user_records[0]['FeedUpdatedDate']);
$min = round(abs($to_time - $from_time) / 60, 0);



if ($min > 10) {
    
    
    
    $sql = "select * FROM tweet_feeds";
    if (!$result = $db->query($sql)) {
        die('There was an error running the query [' . $db->error . ']');
    }

    if ($result->num_rows > 0) {
        $result->free();

        $sql = "Delete FROM tweet_feeds";

        if (!$result = $db->query($sql)) {
            die('There was an error running the query [' . $db->error . ']');
        }
    }

    foreach ($user_records as $user) {

        $mytimeline = new MyTimeLine($user['TwitterName'], 4);
        $timeline = $mytimeline->get();

        $index = 0;
        foreach ($timeline as $tweet) {

            if ($index > 4)
                $db_values .= "('" . htmlentities($tweet[0], ENT_QUOTES, 'UTF-8') . "','" . $tweet[1] . "'," . $user['ID'] . "),";
            $index++;
        }
    }

    //insert all records in database 
	
	if (strpos($db_values,'#mudder') !== false) {
	
    $db_values = substr($db_values, 0, strlen($db_values) - 1);

    $sql = "INSERT INTO tweet_feeds (TweetText,TweetTime,twitter_person_id) Values " . $db_values;

    if (!$result = $db->query($sql)) {
        die('There was an error running the query [' . $db->error . ']');
    }

    $sql = "UPDATE twitter_person SET FeedUpdatedDate = '" . date("Y-m-d H:i:s") . "' where ID > 0";

    if (!$result = $db->query($sql)) {
        die('There was an error running the query [' . $db->error . ']');
    }
	}

As you can see I have tried to add

if (strpos($db_values,'#mudder') !== false) {    
$db_values = substr($db_values, 0, strlen($db_values) - 1);

$sql = "INSERT INTO tweet_feeds (TweetText,TweetTime,twitter_person_id) Values " . $db_values;

to try and add only mudder to the database but it just seems to add any of them.

 

Can anyone hold?

 

Link to comment
Share on other sites

 

if (strpos($db_values,'#mudder') !== false) {    
$db_values = substr($db_values, 0, strlen($db_values) - 1);

$sql = "INSERT INTO twe

 

This code is doing the insert if ANY of them have #mudder in them. You need to NOT add the tweet to the $db_values string unless you want to keep it.

 

        $index = 0;
        foreach ($timeline as $tweet) {
if (strpos($tweet[0], '#mudder') !== false) { // ONLY KEEP IT IF WE WANT IT
            if ($index > 4)
                $db_values .= "('" . htmlentities($tweet[0], ENT_QUOTES, 'UTF-8') . "','" . $tweet[1] . "'," . $user['ID'] . "),";
} // END IF #mudder
            $index++;
        }
By the way, you really should not use htmlentities() on the data going into the database. You should store it raw (with proper escaping -- mysql_real_escape_string). Use htmlentities when you output it in an HTML document.
Link to comment
Share on other sites

Based on ... What? The use of "var" which is right under the DATE it was written?

 

Nope, I'd say it was the constructor method below, which uses PHP4 signature instead of public function __construct($username, $count = 20).

	function myTimeline($username, $count = 20)
	{
		$this->feedUrl = 'http://api.twitter.com/1/statuses/user_timeline/'.$username.'.rss';
		$this->count = $count > 20 ? 20 : $count;
		$this->username = $username;
	}
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.