Posts Tagged ‘PHP’

PHP Stored In MySQL Database

Wednesday, November 24th, 2010

Sometimes it’s helpful to store PHP code in a database and have it execute prior to displaying in the end user’s browser. This can easily be accomplished by using the PHP eval() function.

Assuming the MySQL table appears as follows:

+--------------+
|         code |
+--------------+
| Hello World! |
+--------------+

This can be displayed in the browser by using the following PHP code:

<?php echo $row_table['code']; ?>

Which will appear in the browser as follows: “Hello World!”

However, if the table contains mixed, PHP and HTML content, as follows:

+-----------------------------------------------------+
|                                                code |
+-----------------------------------------------------+
| <p>My PHP script: <?php echo 'Hello World'; ?>.</p> |
+-----------------------------------------------------+

This can be displayed by using the following PHP code:

<?php eval('?>'.$row_table['code'].'<?php '); ?>

The browser will display “My PHP script: Hello World.”

This essentially tells the web server to execute the PHP code between the PHP tags and print the output along with the rest of the string not between the PHP tags.

If however, the MySQL field is storing only PHP code as follows:

+------------------------------------+
|                               code |
+------------------------------------+
| echo 'Three plus five is: '.3 + 5; |
+------------------------------------+

The eval() function may be used as follows:

<?php eval($row_table['code']); ?>

The browser would display “Three plus five is: 8″

PHP Twitter Feed

Tuesday, October 19th, 2010

Here are two simple functions to display Twitter feeds on your website using PHP. The twitter_feed() function pulls the feed from Twitter RSS and returns it as a variable. This function also stores the feed in a database where it can be called in cases where the Twitter RSS feed is unavailable.

//Twitter Feed
function twitter_feed($username, $rss) {
  $hostname_connection = "db_hostname";
  $database_connection = "db_database";
  $username_connection = "db_username";
  $password_connection = "db_password";
  $connection = mysql_pconnect($hostname_connection, $username_connection, $password_connection) or die(mysql_error());
  
  $twitter_feed = '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr><td class="content_twitter" valign="baseline"><a href="http://twitter.com/'.$username.'" target="_blank"><img src="twitter-follow-me.png" alt="Twitter" border="0" align="right"></a>';
  
  $feedURL = $rss;
  $doc = new DOMDocument();
  if($doc->load($feedURL)) {
    $arrFeeds = array();
    foreach ($doc->getElementsByTagName('item') as $node) {
      $itemRSS = array ( 
        'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
        'pubDate' => $node->getElementsByTagName('pubDate')->item(0)->nodeValue
      );
      array_push($arrFeeds, $itemRSS);
    }
    
    $limit = 5;
    for($x=0; $x<$limit; $x++) {
      $title = str_replace('bavotasan: ', '', $arrFeeds[$x]['title']);
      $string = ereg_replace("[[:alpha:]]+://[^<>[:space:]]+[[:alnum:]/]","<a class=\"twitter_link\" href=\"\\0\" target=\"_blank\">\\0</a>", $title); 
      $pattern = '/[#|@][^\s]*/';
      preg_match_all($pattern, $string, $matches);    
      
      foreach($matches[0] as $keyword) {
        $keyword = str_replace(")", "", $keyword);
        $link = str_replace("#", "%23", $keyword);
        $link = str_replace("@", "", $keyword);
        if(strstr($keyword, "@")) {
          $search = '<a href="http://twitter.com/'.$link.'" target="_blank">'.$keyword.'</a>';
        }
        else {
          $link = urlencode($link);
          $search = '<a href="http://twitter.com/#search?q='.$link.'" target="_blank">'.$keyword.'</a>';
        }
        $string = str_replace($keyword, $search, $string);
      }
      $length = strlen($string);
      $string = substr($string, 15, $length);
      $twitter_feed .= '<a href="http://twitter.com/'.$username.'" target="_blank">@'.$username.'</a>: '.$string.'<div class="twitter_time">'.twitter_time($arrFeeds[$x]['pubDate']).' via Twitter</div><br />';
    }
    
    $twitter_feed .= '</td></tr><tr><td align="right"><a href="http://twitter.com/'.$username.'" target="_blank">..::Follow Us!</a></td></tr></table>';
    
    $updateSQL = sprintf('UPDATE twitter SET details="'.$twitter_feed.'" WHERE account="'.$username.'"');

    mysql_select_db($database_connection, $connection);
    mysql_query($updateSQL, $connection) or die(mysql_error());
  }
  
  else {
    mysql_select_db($database_connection, $connection);
    $query_twitter = sprintf('SELECT * FROM twitter WHERE account = "'.$username.'"');
    $twitter = mysql_query($query_twitter, $connection) or die(mysql_error());
    $row_twitter = mysql_fetch_assoc($twitter);
    $totalRows_twitter = mysql_num_rows($twitter);
    
    $twitter_feed = $row_twitter['details'];
  }
  
  return $twitter_feed;
}

The twitter_time() function takes the RSS time and converts it to human readable current server time.

//Twitter Time
function twitter_time($rss_time) {
  $time = date('Hm', strtotime($rss_time));
  $date = date('m/d/Y', strtotime($rss_time));
  
  if($date == system_date()) {
    if(system_time() - $time < 60) {
      $time_result = system_time() - $time;
      if($time_result <= 1) {$time_display = 'about a minute ago';}
      else {$time_display = $time_result.' minutes ago';}
    }
    else {
      $time_result = round(((system_time() - $time) / 60), 0);
      if($time_result == 1) {$time_display = 'about '.$time_result.' hour ago';}
      else {$time_display = 'about '.$time_result.' hours ago';}
    }
  }
  else {
    $time_result = date_difference($date, system_date());
    if($time_result == 1) {$time_display = $time_result.' day ago';}
    else {$time_display = $time_result.' days ago';}

    if($time_result > 7) {
      $date_explode = explode('/', $date);
      if($date_explode[2] == date('Y')) {
        $time = date('g:i A', strtotime($time));
        $date = date('M jS', mktime('00', '00', '00', $date_explode[0], $date_explode[1], $date_explode[2]));
        $time_display = $time.' '.$date;
      }
      else {
        $time = date('g:i A', strtotime($time));
        $date = date('M jS, Y', mktime('00', '00', '00', $date_explode[0], $date_explode[1], $date_explode[2]));
        $time_display = $time.' '.$date;
      }
    }
  }
  
  return $time_display;
}

Usage:

echo twitter_feed('your Twitter username', 'the URL to your Twitter RSS feed page');