Senin, 06 Mei 2013

Membuat tombol Like dan Unlike dengan PHP-Ajax-MySQL

Fitur Like dan Unlike sering kita jumpai di hampir semua situs. dengan ini kita dapat mengetahui apakah artikel, berita, komentar kita disukai atau tidak oleh pengunjung. Beriktu sedikit penggalan program fitur Like dan Unlike seperti di Facebook, menggunakan PHP, Ajax, MySQL.

Struktur Database:
buat struktur database sebagai berikut :

tabel facebook_ip :

CREATE TABLE IF NOT EXISTS `facebook_ip` (
  `userip` varchar(100) NOT NULL,
  `post_id` int(11) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

tabel facebook_likes :

CREATE TABLE IF NOT EXISTS `facebook_likes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `likes` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
dengan contoh data:
INSERT INTO `facebook_likes` (`id`, `likes`, `post_id`) VALUES
(1, 12, 2);

tabel facebook_posts :

CREATE TABLE IF NOT EXISTS `facebook_posts` (
  `p_id` int(11) NOT NULL AUTO_INCREMENT,
  `f_name` varchar(50) NOT NULL,
  `post` varchar(255) NOT NULL,
  `f_image` varchar(50) NOT NULL,
  `date_created` int(11) NOT NULL,
  `userip` varchar(200) NOT NULL,
  PRIMARY KEY (`p_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=6 ;
dengan contoh data :
INSERT INTO `facebook_posts` (`p_id`, `f_name`, `post`, `f_image`, `date_created`, `userip`) VALUES
(2, 'Goedang Teknologi', ' merupakan kumpulan artikel seputar teknologi software dan hardware, serta perkembangan teknologi sekarang in', 'antefer.png', 1367930652, '');

tabel facebook_posts_comments :

CREATE TABLE IF NOT EXISTS `facebook_posts_comments` (
  `c_id` int(11) NOT NULL AUTO_INCREMENT,
  `userip` varchar(200) NOT NULL,
  `comments` text NOT NULL,
  `date_created` int(11) NOT NULL,
  `post_id` int(11) NOT NULL,
  PRIMARY KEY (`c_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=11 ;
dengan contoh data :

INSERT INTO `facebook_posts_comments` (`c_id`, `userip`, `comments`, `date_created`, `post_id`) VALUES
(5, '', 'Membuat Wallpost seperti facebook dengan PHP-Ajax-MySQL. http://antefer.blogspot.com/2013/05/membuat-wallpost-seperti-facebook.html', 1367930652, 2),
(4, '', 'Memiliki Mesin Telusur (Search Engine) sendiri seperti Google dengan Sphider.  http://bit.ly/df9t1L', 1367930652, 2),
(3, '', 'Login Form sederhana dengan PHP, jQuery dan MySQL.  http://antefer.blogspot.com/2013/01/login-form-sederhana-dengan-php-jquery.html', 1367930652, 2),
(2, '', 'Membuat aplikasi registrasi dengan aktivasi email menggunakan PHP. http://bit.ly/df9t1L', 1367930652, 2),
(1, '', 'Cek Username dengan jQuery dan PHP. http://antefer.blogspot.com/2013/04/cek-username-dengan-jquery-dan-php.html', 1367930652, 2),
(6, '', 'Membuat Shoutbox / Chat system dengan PHP - Ajax - Mysql.  http://antefer.blogspot.com/2013/04/membuat-system-chat-dengan-php-ajax.html', 1367930652, 2),
(7, '', 'Membuat Form "Contact Us" dengan Ajax dan PHP. http://antefer.blogspot.com/2013/01/membuat-form-hubungi-kami-dengan-ajax.html', 1367930652, 2),
(8, '', 'Membuat RSS feed dengan PHP dan MySQL. http://antefer.blogspot.com/2013/01/membuat-rss-feed-dengan-php-dan-mysql.html', 1367930652, 2),
(9, '', 'Membuat PDF Reader untuk website dengan FlexPaper.  http://antefer.blogspot.com/2012/12/membuat-pdf-reader-untuk-website-dengan.html', 1367930652, 2),
(10, '', 'Paginasi Data menggunakan PHP-MySQL-Ajax. http://antefer.blogspot.com/2012/12/paginasi-data-menggunakan-php-mysql-ajax.html', 1367930652, 2);

dbcon.php :
<?
$host="localhost";
$user="447865";//username
$pass="mysql-antefer";//password
$base="447865";//database
$connect=mysql_connect($host,$user,$pass);
mysql_select_db($base, $connect);
?>
Kode jQuery :
 // <![CDATA[ 

 $(document).ready(function(){ 
 
  $('.ViewComments').livequery("click",function(e){
   
   var parent  = $(this).parent();
   var getID   =  parent.attr('id').replace('collapsed-','');
   
   var total_comments = $("#totals-"+getID).val();
      
   $("#loader-"+getID).html('<img src="loader.gif" alt="" />');
   
   $.post("view_comments.php?postId="+getID+"&totals="+total_comments, {
 
   }, function(response){
    
    $('#CommentPosted'+getID).prepend($(response).fadeIn('slow'));
    $('#collapsed-'+getID).hide();
    
   });
  }); 
  
  /// like 
  
  $('.LikeThis').livequery("click",function(e){
   
   var getID   =  $(this).attr('id').replace('post_id','');
   
   $("#like-loader-"+getID).html('<img src="loader.gif" alt="" />');
   
   $.post("like.php?postId="+getID, {
 
   }, function(response){
    
    $('#like-stats-'+getID).html(response);
    
    $('#like-panel-'+getID).html('<a href="javascript: void(0)" id="post_id'+getID+'" class="Unlike">Tidak suka</a>');
    
    $("#like-loader-"+getID).html('');
   });
  }); 
  
  /// unlike 
  
  $('.Unlike').livequery("click",function(e){
   
   var getID   =  $(this).attr('id').replace('post_id','');
   
   $("#like-loader-"+getID).html('<img src="loader.gif" alt="" />');
   
   $.post("unlike.php?postId="+getID, {
 
   }, function(response){
    
    $('#like-stats-'+getID).html(response);
    
    $('#like-panel-'+getID).html('<a href="javascript: void(0)" id="post_id'+getID+'" class="LikeThis">Suka</a>');
    
    $("#like-loader-"+getID).html('');
   });
  }); 
  
  
  
 }); 

 // ]]>
like.php :
<?php
 include('dbcon.php');
 
 if($_REQUEST['postId'])
 {
  $userip = $_SERVER['REMOTE_ADDR'];
  
  mysql_query("update facebook_likes set likes=likes+1 where post_id= ".$_REQUEST['postId']);
  
  mysql_query("INSERT INTO facebook_ip (userip,post_id) VALUES('".$userip."','".$_REQUEST['postId']."')");
  
  $total_likes = mysql_query("SELECT * FROM facebook_likes where post_id = ".$_REQUEST['postId']." ");
  $likes = mysql_fetch_array($total_likes);
  $likes = $likes['likes'];
 }
 echo $likes;
?>

unlike.php :
<?php
 include('dbcon.php');
 
 if($_REQUEST['postId'])
 {
  $userip = $_SERVER['REMOTE_ADDR'];
  
  mysql_query("update facebook_likes set likes=likes-1 where post_id= ".$_REQUEST['postId']);
  
  mysql_query("delete from facebook_ip where userip=".$userip." AND post_id = ".$_REQUEST['postId']);
  
  $total_likes = mysql_query("SELECT * FROM facebook_likes where post_id = ".$_REQUEST['postId']." ");
  $likes = mysql_fetch_array($total_likes);
  $likes = $likes['likes'];
 }
 echo $likes;
?>

view_comments.php :
 <?php
 include('dbcon.php');
 
 function clickable_link($text = '')
 {
  $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\1:", $text);
  $ret = ' ' . $text;
  $ret = preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="\2" target="_blank" rel="no_follow">\2</a>", $ret);
  
  $ret = preg_replace("#(^|[n ])((www|ftp).[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="http://\2" target="_blank">\2</a>", $ret);
  $ret = preg_replace("#(^|[n ])([a-z0-9&-_.]+?)@([w-]+.([w-.]+.)*[w]+)#i", "\1<a href="mailto:\2@\3">\2@\3</a>", $ret);
  $ret = substr($ret, 1);
  return $ret;
 }
 
 $comments = mysql_query("SELECT *,UNIX_TIMESTAMP() - date_created AS CommentTimeSpent FROM facebook_posts_comments where post_id = ".$_REQUEST['postId']." order by date_created asc limit 4, ".$_REQUEST['totals']);
  
 $comment_num_row = mysql_num_rows(@$comments);
 
 if($comment_num_row > 0)
 {
  while ($rows = mysql_fetch_array($comments))
  {
   $days2 = floor($rows['CommentTimeSpent'] / (60 * 60 * 24));
   $remainder = $rows['CommentTimeSpent'] % (60 * 60 * 24);
   $hours = floor($remainder / (60 * 60));
   $remainder = $remainder % (60 * 60);
   $minutes = floor($remainder / 60);
   $seconds = $remainder % 60; ?>
   
   <div class="commentPanel" align="left">
    <img src="antefer.png" width="35" class="CommentImg" style="float:left;" alt="" />
    <label class="postedComments">
     <?php  echo clickable_link($rows['comments']);?>
    </label>
    <br clear="all" />
    <span style="margin-left:43px; color:#666666; font-size:11px">
    <?php
    
    if($days2 > 0)
    echo date('F d Y', $rows['date_created']);
    elseif($days2 == 0 && $hours == 0 && $minutes == 0)
    echo "beberapa detik yang lalu";  
    elseif($days2 == 0 && $hours == 0)
    echo $minutes.' menit yang lalu';
    elseif($days2 == 0 && $hours > 0)
    echo $hours.' jam yang lalu';
    else
    echo "beberapa detik yang lalu"; 
    ?>
    </span>
    
   </div>
  <?php
  }
 }?>
 

post.php : 
 <?php
 include('dbcon.php');
 
 function clickable_link($text = '')
 {
  $text = preg_replace('#(script|about|applet|activex|chrome):#is', "\1:", $text);
  $ret = ' ' . $text;
  $ret = preg_replace("#(^|[n ])([w]+?://[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="\2" target="_blank" rel="no_follow">\2</a>", $ret);
  
  $ret = preg_replace("#(^|[n ])((www|ftp).[w#$%&~/.-;:=,?@[]+]*)#is", "\1<a href="http://\2" target="_blank">\2</a>", $ret);
  $ret = preg_replace("#(^|[n ])([a-z0-9&-_.]+?)@([w-]+.([w-.]+.)*[w]+)#i", "\1<a href="mailto:\2@\3">\2@\3</a>", $ret);
  $ret = substr($ret, 1);
  return $ret;
 }
 
 $result = mysql_query("SELECT *,
 UNIX_TIMESTAMP() - date_created AS TimeSpent FROM facebook_posts order by p_id desc limit 0,10");
 
 $userip = $_SERVER['REMOTE_ADDR'];
 
 while ($row = mysql_fetch_array($result))
 {
  $like_ip = mysql_query("SELECT count(*) FROM facebook_ip where post_id = ".$row['p_id']." AND userip='".$userip."'");
  $like_ip_num = mysql_num_rows($like_ip);
  
  $total_comments = mysql_query("SELECT count(*) FROM facebook_posts_comments where post_id = ".$row['p_id']." order by date_created asc");
  $records = mysql_fetch_array($total_comments);
  $records = $records[0];
  
  $total_likes = mysql_query("SELECT * FROM facebook_likes where post_id = ".$row['p_id']." ");
  $likes = mysql_fetch_array($total_likes);
  $likes = $likes['likes'];
  
  $comments = mysql_query("SELECT *,
  UNIX_TIMESTAMP() - date_created AS CommentTimeSpent FROM facebook_posts_comments where post_id = ".$row['p_id']." order by date_created asc limit 0,4");
  
  $comment_num_row = mysql_num_rows(@$comments);?>
  
    <div class="friends_area">

    <img src="antefer.png" style="float:left;" width="60" alt="" />

     <label style="float:left" class="name">

     <b><a href="http://www.facebook.com/GoedangTeknologi" target="_blank"><?php echo $row['f_name'];?></a></b>

     <em><?php  echo clickable_link($row['post']);?></em>
     <br clear="all" />

     <span>
     <?php  
     
      $days = floor($row['TimeSpent'] / (60 * 60 * 24));
   $remainder = $row['TimeSpent'] % (60 * 60 * 24);
   $hours = floor($remainder / (60 * 60));
   $remainder = $remainder % (60 * 60);
   $minutes = floor($remainder / 60);
   $seconds = $remainder % 60;
   
   if($days > 0)
   echo date('F d Y', $row['date_created']);
   elseif($days == 0 && $hours == 0 && $minutes == 0)
   echo "beberapa detik yang lalu";  
   elseif($days == 0 && $hours == 0)
   echo $minutes.' menit yang lalu';
   elseif($days == 0 && $hours > 0)
   echo $hours.' jam yang lalu';
   else
   echo "beberapa detik yang lalu"; ?>
     
     </span>
     
      &nbsp;&nbsp;&nbsp;&nbsp;
   
   <span id="like-panel-<?php  echo $row['p_id']?>">
    
   <?php
   if($like_ip_num > 0){?>
    <a href="javascript: void(0)" id="post_id<?php  echo $row['p_id']?>" class="LikeThis">Suka</a>
   <?php }else{?>
    <a href="javascript: void(0)" id="post_id<?php  echo $row['p_id']?>" class="Unlike">Tidak suka</a>
   <?php }?>
    
   </span>
   
     </label>
     <?php
   $userip = $_SERVER['REMOTE_ADDR'];
   if($row['userip'] == $userip){?>
     <a href="#" class="delete"> hapus</a>
     <?php
   }?>
   
   <input type="hidden" value="<?php echo $records?>" id="totals-<?php  echo $row['p_id'];?>" />
   
      <br clear="all" />
   
   <div class="commentPanel" align="left">
    <img src="like.png" style="float:left;" alt="" />
    
    <span id="like-stats-<?php  echo $row['p_id'];?>"> <?php echo $likes;?> </span> orang yang suka ini.
    
    <span id="like-loader-<?php  echo $row['p_id']?>">&nbsp;</span>
   </div>
   <?php
   if ($records > 4)
   {
    $collapsed = true;?>
   <div class="commentPanel" id="collapsed-<?php  echo $row['p_id'];?>" align="left">
    <img src="cicon.png" style="float:left;" alt="" />
    <a href="javascript: void(0)" class="ViewComments">
    Tampilkan <?php echo $records;?> komentar 
    </a>
    <span id="loader-<?php  echo $row['p_id']?>">&nbsp;</span>
   </div>
   <?php
   }?>
   <div id="CommentPosted<?php  echo $row['p_id']?>">
    <?php
    
    if($comment_num_row > 0)
    {
     while ($rows = mysql_fetch_array($comments))
     {
      $days2 = floor($rows['CommentTimeSpent'] / (60 * 60 * 24));
      $remainder = $rows['CommentTimeSpent'] % (60 * 60 * 24);
      $hours = floor($remainder / (60 * 60));
      $remainder = $remainder % (60 * 60);
      $minutes = floor($remainder / 60);
      $seconds = $remainder % 60;      
      ?>
     <div class="commentPanel" align="left">
      <img src="antefer.png" width="35" class="CommentImg" style="float:left;" alt="" />
      <label class="postedComments">
       <?php  echo clickable_link($rows['comments']);?>
      </label>
      <br clear="all" />
      <span style="margin-left:43px; color:#666666; font-size:11px">
      <?php
      
      if($days2 > 0)
      echo date('F d Y', $rows['date_created']);
      elseif($days2 == 0 && $hours == 0 && $minutes == 0)
      echo "beberapa detik yang lalu";  
      elseif($days2 == 0 && $hours == 0)
      echo $minutes.' menit yang lalu';
      elseif($days == 0 && $hours > 0)
      echo $hours.' jam yang lalu';
      else
      echo "beberapa detik yang lalu"; 
      ?>
      </span>
      
     </div>
     <?php
     }?>    
     <?php
    }?>
   </div>
    </div>
 <?php
 }?>
 

Demikian tentang membuat tombol Like dan Unlike seperti facebook menggunakan PHP-Ajax-MySQL. Untuk demo disini. Dan untuk download source code disini.

Semoga bermanfaat...

Tidak ada komentar:

Posting Komentar

Hubungi saya

Nama

Email *

Pesan *



* maaf buat teman-teman yang belum di respons komentarnya di disqus (karena penullisnys sok sibuk sie...), bisa hubungi lewat sini ya...

Tentang Blog

Banyak sekali informasi-informasi tentang dunia TI (Teknologi Informasi) yang sekarang merupakan sebuah kebutuhan yang boleh dibilang sudah menjadi kebutuhan utama dalam pekerjaan. Tetapi teknologi juga sering digunakan untuk kepentingan yang merugikan orang lain, misal carding, cracking, dan lain-lain. Dengan internet saya mendapat banyak sekali masukkan yang membangun, dengan blog ini saya ingin berbagi pengalaman tentang ilmu komputer yang saya dapat.

Penulis

authorHallo, Nama saya Andreas Thedy Feriyanto.