Please support us by disabling ad blocker for smarttutorials.net ...

Demo Facebook like Button Application Using PHP, MySQL, jQuery and Ajax

Posted by & filed under Ajax, FACEBOOK, JAVASCRIPT, JQUERY, MYSQL, PHP.

This small demo application that demonstrates Live Facebook like Button Using PHP, MySQL, jQuery and Ajax. I will walk you through step by step making of this application. Please follow every step and finally you make it this demo appliaction yourself. If you completes this application you will come know HTML DOM updation using jQuery and some of Jquery ajax techniques.

 

 

Demo Facebook Like Button Application

Demo Facebook like button application using php mysql jquery and Ajax

Step 1:

Create new database in your MySQL database in the name of “facebook”, and now create following three tables using following SQL queries.

1. users

CREATE  TABLE IF NOT EXISTS `facebook`.`users` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `name` VARCHAR(50) NOT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB
AUTO_INCREMENT = 11
DEFAULT CHARACTER SET = latin1;

2. likes

CREATE  TABLE IF NOT EXISTS `facebook`.`likes` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `count` INT(11) NOT NULL ,
  PRIMARY KEY (`id`) )
ENGINE = InnoDB
AUTO_INCREMENT = 5
DEFAULT CHARACTER SET = latin1;

3. user_likes

CREATE  TABLE IF NOT EXISTS `facebook`.`user_likes` (
  `id` INT(11) NOT NULL AUTO_INCREMENT ,
  `users_id` INT(11) NOT NULL ,
  `likes_id` INT(11) NOT NULL ,
  PRIMARY KEY (`id`) ,
  INDEX `fk_user_likes_users_idx` (`users_id` ASC) ,
  INDEX `fk_user_likes_likes1_idx` (`likes_id` ASC) ,
  CONSTRAINT `fk_user_likes_users`
    FOREIGN KEY (`users_id` )
    REFERENCES `facebook`.`users` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION,
  CONSTRAINT `fk_user_likes_likes1`
    FOREIGN KEY (`likes_id` )
    REFERENCES `facebook`.`likes` (`id` )
    ON DELETE NO ACTION
    ON UPDATE NO ACTION)
ENGINE = InnoDB
AUTO_INCREMENT = 42
DEFAULT CHARACTER SET = latin1;

 

 

Here above tables relationship diagrams

demo facebook like button application  database designStep 2:

Create index.php file and add following scripts in it.

<!---
Site : http:www.smarttutorials.net
 Author :muni
--->

<!DOCTYPE html>
<html>
	<head>
		<title>Facebook like button Demo with Responsive Design</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<!-- Bootstrap -->
		<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">

		<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
		<!--[if lt IE 9]>
		<script src="../../assets/js/html5shiv.js"></script>
		<script src="../../assets/js/respond.min.js"></script>
		<![endif]-->
		<style>
			.container {
				margin-top: 150px;
			}
			p {
				margin-left: 170px;
			}
			button {
				margin-left: 100px;
			}
			.error {
				color: #B94A48;
			}
			.form-horizontal {
				margin-bottom: 0px;
			}
		</style>
	</head>
	<body>
		<div class="container">
			<div class="col-xs-12 col-sm-8 col-md-8 col-xs-offset-4 col-sm-offset-3 col-md-offset-3">
				<p>
					Please Eneter Your Name for Demo Purpose
				</p>
				<hr>
				<form class="form-horizontal" role="form" id='login' action="facebook.php" method="post">
					<div class="form-group">
						<div class="col-lg-10">
							<input type="text" class="form-control" id="name" name="name" placeholder="Enter your name">
							<span class="help-block"></span>
						</div>
					</div>
					<br>
					<br>
					<div class="col-lg-6 text-center">
						<button type="submit" class="btn btn-success btn-block">
							Primary
						</button>
					</div>
				</form>
			</div>
		</div>

		<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
		<script src="js/jquery-1.10.2.min.js"></script>
		<!-- Include all compiled plugins (below), or include individual files as needed -->
		<script src="js/bootstrap.min.js"></script>
		<script src="js/jquery.validate.min.js"></script>
		<script>
			$(document).ready(function() {
				$("#login").validate({
					submitHandler : function() {
						if (form.valid()) {
							return true;
						} else {
							return false;
						}

					},
					rules : {
						name : {
							required : true,
							minlength : 3,
							remote : {
								url : "check_name.php",
								type : "post",
								data : {
									username : function() {
										return $("#name").val();
									}
								}
							}
						}
					},
					messages : {
						name : {
							required : "Please enter your name",
							remote : "Name is already taken, Please choose some other name"
						}
					},
					errorPlacement : function(error, element) {
						$(element).closest('.form-group').find('.help-block').html(error.html());
					},
					highlight : function(element) {
						$(element).closest('.form-group').removeClass('has-success').addClass('has-error');
					},
					success : function(element, lab) {
						var messages = new Array("That's Great!", "Looks good!", "You got it!", "Great Job!", "Smart!", "That's it!");
						var num = Math.floor(Math.random() * 6);
						$(lab).closest('.form-group').find('.help-block').text(messages[num]);
						$(lab).addClass('valid').closest('.form-group').removeClass('has-error').addClass('has-success');
					}
				});
			});
		</script>
	</body>
</html>

It receives users name for demo purpose.

Step 2:

Create config.php to maintain Database connection in single file.

<?php
/*
 * Site : http:www.smarttutorials.net
 * Author :muni
 * 
 */
define('DB_HOST', 'localhost');
define('DB_NAME', 'facebook');
define('DB_USER','root');
define('DB_PASSWORD','');

$con=mysql_connect(DB_HOST,DB_USER,DB_PASSWORD) or die("Failed to connect to MySQL: " . mysql_error());
$db=mysql_select_db(DB_NAME,$con) or die("Failed to connect to MySQL: " . mysql_error());

?>

Step 3:

Now create facebook.php file and add the following scripts in it.

<?php
/*
 * Site : http:www.smarttutorials.net
 * Author :muni
 * 
 */

require_once 'config.php';

session_start();

 if(!empty($_POST['name'])){
     $name=$_POST['name'];
     mysql_query("INSERT INTO users (id, name)VALUES ('NULL','$name')") or die(mysql_error());
     $_SESSION['name']= $name;
     $_SESSION['id'] = mysql_insert_id();
 }

 if(!empty($_SESSION['name'])){
?>
<!DOCTYPE html>
<html class="no-js">
	<head>
		<title>Facebook like button Demo with Responsive Design</title>
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<!-- Bootstrap -->
		<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
		<link href="css/font-awesome.min.css" rel="stylesheet" media="screen">
		<link href="css/font-awesome-ie7.min.css" rel="stylesheet" media="screen">
		<link href="css/style.css" rel="stylesheet" media="screen">

		<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
		<!--[if lt IE 9]>
		<script src="../../assets/js/html5shiv.js"></script>
		<script src="../../assets/js/respond.min.js"></script>
		<![endif]-->
		<style>
		</style>
	</head>
	<body>
		<div class="container">
			<h1 class="text-center">Facebook Like Button Demo with Responsive Design</h1>
			<hr>
			<div class="col-xs-15 col-sm-10 col-md-10 col-xs-offset-3 col-sm-offset-2 col-md-offset-2">
				<?php $res = mysql_query("select id,count as count from likes") or die(mysql_error());
                while($result=mysql_fetch_array($res)){           
				?>
				<div class="image_container">
					<img src='image/image<?php echo $result['id']; ?>.png' class="img-responsive img-thumbnail"/>
					<p id="like_container<?php echo $result['id']; ?>" class='like_container'>
						<a id="<?php echo $result['id']; ?>" class="btn like" href="javascript:;"> <i class="icon-hand-down"></i> <span class="dis"> Unlike Me!!</span></a><span class="score"><?php echo $result['count']; ?></span>people like this

					</p>
				</div>
				<?php } ?>
                <input id="name" type='hidden' value="<?php echo $_SESSION['name']; ?>"/>
                <input id="id" type='hidden' value="<?php echo $_SESSION['id']; ?>"/>
			</div>
		</div>

		<footer>	    
		    <p class="text-center" id="foot">&copy;<a href="http://smarttutorials.net/" target="_blank">Smart Tutorials </a>2013</p>
		</footer>

		<div class="loader"><p>Plaese Wait!!!!</p></div>

		<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
		<script src="js/jquery-1.10.2.min.js"></script>
		<!-- Include all compiled plugins (below), or include individual files as needed -->
		<script src="js/bootstrap.min.js"></script>

		<script>
			$(window).load(function() {
				$(".loader").fadeOut("slow");
			});

			$(document).on('mouseover', '.like', function() {
				id = $(this).attr('id');
				name = $('#name').val();
				user_id = $('#id').val();
				container = $(this).closest('.like_container').attr('id');
				$.ajax({
					type : "POST",
					url : "check_name.php",
					data : {
						id : id,
						user_id : user_id,
						flag : 'check_unique'
					},
					async : false,
					success : function(data) {
						if (data > 0) {
							$('#' + container).find('i').removeClass('icon-hand-up').addClass('icon-hand-down');
							$('#' + container).find('.dis').html('Unlike Me!!');
						}
					}
				});

				$('#' + id).mouseleave(function() {
					$('#' + container).find('i').removeClass('icon-hand-down').addClass('icon-hand-up');
					$('#' + container).find('.dis').html('Like Me!!');
				});
			});

			$(document).on('click', '.like', function() {
				id = $(this).attr('id');
				user_id = $('#id').val();
				container = $(this).closest('.like_container').attr('id');
				$.ajax({
					type : "POST",
					url : "check_name.php",
					data : {
						id : id,
						user_id : user_id,
						flag1 : 'update'
					},
					async : false,
					success : function(data) {
						$('#' + container).find('.score').html(data);
					}
				});
			});

		</script>

	</body>
</html>

<?php } ?>

Step 4:

Create style.css file and add following css styles in it.

/*
 * Site : http:www.smarttutorials.net
 * Author :muni
 * 
 */

body {
	/*background: #E26A6A;
	background:#98E1ED;*/
	background:#42D39B;
	color:#fff;
	position: relative;
}
.container {
	margin-top: 30px;
}
@font-face {
	font-family: Lobster;
	src: url('Lobster.otf');
}
h1 {
	font-family: Lobster;
	color:#fff;
	font-size: 50px;
}
.image_container {
	margin-bottom: 30px;
}
a, a:hover{text-decoration: none; color:#fff;}
p a {
	margin-left: 250px;
}

#foot a{margin-left: 5px !important;}
.score {
	margin-left: 10px;
	margin-right: 10px;
}
footer{background:#E26A6A;height:80px;padding-top:20px;}

.loader {
	position: fixed;
	left: 0px;
	top: 0px;
	width: 100%;
	height: 100%;
	z-index: 9999;
	background: url(../image/loader.gif) 50% 50% no-repeat rgb(249,249,249);
}

Step 5:

Finally create ajax.php file which handles all the ajax request from  other PHP files.

<?php

/*
 * Site : http:www.smarttutorials.net
 * Author :muni
 * 
 */
 require_once 'config.php';

 if(!empty($_POST['name'])){
     $name=$_POST['name'];
     $res=mysql_query("select count(name) as count from users where name='$name'") or die(mysql_error()); 
     $count=mysql_fetch_array($res);
     if($count[0]==0){
         echo 'true';
     }else{
         echo 'false';
     }
 }

 if(isset($_POST['flag'])){
     $like_id=$_POST['id'];
     $user_id=$_POST['user_id'];
     $res=mysql_query("select count(*) as count from user_likes where like_id=$like_id and user_id=$user_id") or die(mysql_error()); 
     $count=mysql_fetch_array($res);
     echo $count[0];
 }

 if(isset($_POST['flag1'])){
     $like_id=$_POST['id'];
     $user_id=$_POST['user_id'];

     $res=mysql_query("select count(*) as count from user_likes where like_id=$like_id and user_id=$user_id") or die(mysql_error()); 
     $count=mysql_fetch_array($res);
     $count[0];

     if($count[0]==0){
         mysql_query("INSERT INTO user_likes (id, like_id,user_id)VALUES ('NULL','$like_id','$user_id')") or die(mysql_error());
         mysql_query("update likes set count=count+1 where id=$like_id") or die(mysql_error()); 
        $res=mysql_query("select count from likes where id=$like_id") or die(mysql_error()); 
        $count=mysql_fetch_array($res);
        echo $count[0];
     }else{
         mysql_query("DELETE FROM user_likes where like_id=$like_id and user_id=$user_id") or die(mysql_error());
         mysql_query("update likes set count=count-1 where id=$like_id") or die(mysql_error()); 
         $res=mysql_query("select count from likes where id=$like_id") or die(mysql_error()); 
         $count=mysql_fetch_array($res);
         echo $count[0];    
     }

 }
?>

 

 

 

 

 .

Download Premium Only Scripts & 80+ Demo scripts Instantly at just 1.95 USD per month + 10% discount to all Exclusive Scripts

If you want any of my script need to be customized according to your business requirement,

Please feel free to contact me [at] muni[at]smarttutorials.net

Note: But it will be charged based on your customization requirement

Get Updates, Scripts & Other Useful Resources to your Email

Join 10,000+ Happy Subscribers on feedburner. Click to Subscribe (We don't send spam)
Every Email Subsciber could have access to download 100+ demo scripts & all future scripts.

  • A.

    Why I can’t download this?

  • You must be subscriber to download the script..

Get Instant Script Download Access!