title: Integrating a Bookmark App with a Social Networking Site
body: <p>I have a perfectly functional bookmarking app. As of now, it's non-exclusive; when I press "save" bookmark it sends the url to a general table in the DB. I need to figure out how to integrate this with an online community, so its <strong>user specific</strong> and each time a user "saves" a story, it sends the url to that user's row in the DB and outputs back to that user's profile. </p>
  
  <p>Code is below.
  Here's a demo:
  <a href="http://demo.tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/demo.php" rel="nofollow">http://demo.tutorialzine.com/2010/04/simple-bookmarking-app-php-javascript-mysql/demo.php</a></p>
  
  <p>Bookmark.php</p>
  
  <pre><code> &lt;?php
  
   // Error reporting:
   error_reporting(E_ALL^E_NOTICE);
  
   require "connect.php";
   require "functions.php";
  
   // Setting the content-type header to javascript:
  header('Content-type: application/javascript');
  
   // Validating the input data
  if(empty($_GET['url']) || empty($_GET['title']) || !validateURL($_GET['url'])) die();
  
  // Sanitizing the variables
  $_GET['url'] = sanitize($_GET['url']);
  $_GET['title'] = sanitize($_GET['title']);
  
  // Inserting, notice the use of the hash field and the md5 function:
  mysql_query("   INSERT INTO bookmark_app (hash,url,title)
              VALUES (
                  '".md5($_GET['url'])."',
                  '".$_GET['url']."',
                  '".$_GET['title']."'
              )");
  
  $message = '';
  if(mysql_affected_rows($link)!=1)
  {
  $message = 'You have already saved this Headline';
  }
  else
  $message = 'The URL was shared!';
  
  
   ?&gt;
  
   /* JavaScript Code */
  
    function displayMessage(str)
     {
  // Using pure JavaScript to create and style a div element
  
  var d = document.createElement('div');
  
  with(d.style)
  {
      // Applying styles:
  
      position='fixed';
      width = '350px';
      height = '20px';
      top = '50%';
      left = '50%';
      margin = '-30px 0 0 -195px';
      backgroundColor = '#f7f7f7';
      border = '1px solid #ccc';
      color = '#777';
      padding = '20px';
      fontSize = '18px';
      fontFamily = '"Myriad Pro",Arial,Helvetica,sans-serif';
      textAlign = 'center';
      zIndex = 100000;
  
      textShadow = '1px 1px 0 white';
  
      MozBorderRadius = "12px";
      webkitBorderRadius = "12px";
      borderRadius = "12px";
  
      MozBoxShadow = '0 0 6px #ccc';
      webkitBoxShadow = '0 0 6px #ccc';
      boxShadow = '0 0 6px #ccc';
   }
  
   d.setAttribute('onclick','document.body.removeChild(this)');
  
     // Adding the message passed to the function as text:
   d.appendChild(document.createTextNode(str));
  
     // Appending the div to document
   document.body.appendChild(d);
  
     // The message will auto-hide in 3 seconds:
  
   setTimeout(function(){
      try{
          document.body.removeChild(d);
      }   catch(error){}
   },3000);
       }
  
     &lt;?php 
  
   // Adding a line that will call the JavaScript function:
   echo 'displayMessage("'.$message.'");';
  
   ?&gt;
  </code></pre>
  
  <p>Connect.php
      
  
  <pre><code>/* Database config */
  
  $db_host        = 'xxxxx';
  $db_user        = 'xxxxx';
  $db_pass        = 'xxxxx';
  $db_database    = 'xxxxx'; 
  
  /* End config */
  
  
  $link = @mysql_connect($db_host,$db_user,$db_pass) or die('Unable to establish a DB connection');
  
  mysql_set_charset('utf8');
  mysql_select_db($db_database,$link);
  
  ?&gt;
  </code></pre>
  
  <p>Demo.php
      
  
  <pre><code>// Error reporting:
  error_reporting(E_ALL^E_NOTICE);
  
  require "connect.php";
  require "functions.php";
  
  $url = 'http://'.$_SERVER['SERVER_NAME'].dirname($_SERVER["REQUEST_URI"]);
  
  ?&gt;
  
  &lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;
  &lt;html xmlns="http://www.w3.org/1999/xhtml"&gt;
  &lt;head&gt;
  &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt;
  &lt;title&gt;Simple Bookmarking App With PHP, JavaScript &amp;amp; MySQL | Tutorialzine demo&lt;/title&gt;
  
  &lt;link rel="stylesheet" type="text/css" href="styles.css" /&gt;
  
  &lt;/head&gt;
  
  &lt;body&gt;
  
  &lt;h1&gt;Bookmarking App...&lt;/h1&gt;
  &lt;h2&gt;&lt;a href="http://google.com"&gt;Return to the homepage &amp;raquo;&lt;/a&gt;&lt;/h2&gt;
  
  &lt;div id="main"&gt;
  
  &lt;div class="bookmarkHolder"&gt;
  
      &lt;!--    The link contains javascript functionallity which is preserved
              when the user drops it to their bookmark/favorites bar  --&gt;
  
        &lt;a href="javascript:(function(){var jsScript=document.createElement('script');
     jsScript.setAttribute('type','text/javascript');
     jsScript.setAttribute('src', '&lt;?php echo  $url?&gt;/bookmark.php?url='+encodeURIComponent(location.href)+'&amp;amp;title='+encodeURIComponent(document.title));
    document.getElementsByTagName('head')[0].appendChild(jsScript);
    })();" class="bookmarkButton"&gt;Bookmark this!&lt;/a&gt;
  
      &lt;em&gt;Drag this button to your bookmarks bar and click it when visiting a web site. The title and URL of the page will be saved below.&lt;/em&gt;
     &lt;/div&gt;
  
    &lt;ul class="latestSharesUL"&gt;
      &lt;?php
  
      $shares = mysql_query("SELECT * FROM bookmark_app ORDER BY id DESC LIMIT 6");
  
      while($row=mysql_fetch_assoc($shares))
      {
          // Shortening the title if it is too long:
          if(mb_strlen($row['title'],'utf-8')&gt;80)
              $row['title'] = mb_substr($row['title'],0,80,'utf-8').'..';
  
          // Outputting the list elements:
          echo '
          &lt;li&gt;
              &lt;div class="title"&gt;&lt;a href="'.$row['url'].'" class="bookmrk"&gt;'.$row['title'].'&lt;/a&gt;&lt;/div&gt;
              &lt;div class="dt"&gt;'.relativeTime($row['dt']).'&lt;/div&gt;
          &lt;/li&gt;';
      }
  
          ?&gt;
      &lt;/ul&gt;
  
   &lt;/div&gt;
  
   &lt;/body&gt;
   &lt;/html&gt;
  </code></pre>
  
  <p>Functions.php
       
  
  <pre><code> /* Helper functions */
  
   function validateURL($str)
   {
  return preg_match('/(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;amp;:\/~\+#]* [\w\-\@?^=%&amp;amp;\/~\+#])?/i',$str);
   }
  
   function sanitize($str)
   {
  if(ini_get('magic_quotes_gpc'))
      $str = stripslashes($str);
  
  $str = strip_tags($str);
  $str = trim($str);
  $str = htmlspecialchars($str);
  $str = mysql_real_escape_string($str);
  
  return $str;
   }
  
  
   function relativeTime($dt,$precision=2)
   {
  if(is_string($dt)) $dt = strtotime($dt);
  
  $times=array(   365*24*60*60    =&gt; "year",
                  30*24*60*60     =&gt; "month",
                  7*24*60*60      =&gt; "week",
                  24*60*60        =&gt; "day",
                  60*60           =&gt; "hour",
                  60              =&gt; "minute",
                  1               =&gt; "second");
  
  $passed=time()-$dt;
  
  if($passed&lt;5)
  {
      $output='less than 5 seconds ago';
  }
  else
  {
      $output=array();
      $exit=0;
  
      foreach($times as $period=&gt;$name)
      {
          if($exit&gt;=$precision || ($exit&gt;0 &amp;&amp; $period&lt;60)) break;
  
          $result = floor($passed/$period);
          if($result&gt;0)
          {
              $output[]=$result.' '.$name.($result==1?'':'s');
              $passed-=$result*$period;
              $exit++;
          }
          else if($exit&gt;0) $exit++;
      }
  
      $output=implode(' and ',$output).' ago';
    }
  
    return $output;
    }
  
   // Defining fallback functions for mb_substr and 
   // mb_strlen if the mb extension is not installed:
  
   if(!function_exists('mb_substr'))
   {
  function mb_substr($str,$start,$length,$encoding)
  {
      return substr($str,$start,$length);
  }
   }
  
   if(!function_exists('mb_strlen'))
   {
  function mb_strlen($str,$encoding)
  {
      return strlen($str);
  }
   }
   ?&gt;
  </code></pre>
  
  <p>Table.sql</p>
  
  <pre><code>CREATE TABLE `bookmark_app` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `hash` varchar(32) collate utf8_unicode_ci NOT NULL default '',
  `url` text collate utf8_unicode_ci NOT NULL,
  `title` text collate utf8_unicode_ci NOT NULL,
  `dt` timestamp NOT NULL default CURRENT_TIMESTAMP,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `hash` (`hash`)
  ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  </code></pre>