Tag

jquery

Browsing

How to Create Like & Unlike code like FB using PHP, MySQL and jQuery

How to Create Like & Unlike code like FB using PHP, MySQL and jQuery

In this tutorials we are going to learn How to Create Like & Unlike code using PHP, MySQL and jQuery.

Rating system is very useful for every web project. Through this system, web admin can track the visitors like and dislike. Also it will help webmaster to understand the visitors choices and make their website more interactive with the visitors.

Demo       |

We have made the simple rating or like or unlike code system using PHP, MySQL, jQuery and Ajax. This rating system take the visitors like or dislike with jQuery and Ajax.

Step 1: Create database ‘like’ table using MySQL query.

CREATE TABLE `likes` (
  `id` int(5) NOT NULL AUTO_INCREMENT,
  `pid` int(10) NOT NULL,
  `like` int(10) NOT NULL,
  `unlike` int(10) NOT NULL,
  `uid` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1;

Step 2: Create database ‘products‘ table using MySQL query.

CREATE TABLE `products` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_name` varchar(255) NOT NULL,
  `price` double(10,2) NOT NULL DEFAULT '0.00',
  `status` int(2) NOT NULL DEFAULT '1',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4;

-- 
-- Dumping data for table `products`
-- 

INSERT INTO `products` VALUES (1, 'developer desks design book', 20.00,  1);
INSERT INTO `products` VALUES (2, 'Developer desks login tutorials', 10.00, , 1);
INSERT INTO `products` VALUES (3, 'developer desks coding book', 100.00,  1);

Step 3: Connect DB function with db coding.

<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$connection = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_DATABASE);
?>

Step 4: Index.php files have Main file show products list and and like buttons:

<?php
session_start();
include("db.php");
if(!isset($_SESSION['user']))
{
    $_SESSION['user'] = session_id();
}
$uid = $_SESSION['user'];  // set your user id settings

if($_POST)  // AJAX request received section
{
    $pid    = mysqli_real_escape_string($connection,$_POST['pid']);  // product id
    $op     = mysqli_real_escape_string($connection,$_POST['op']);  // like or unlike op
    

    if($op == "like")
    {
        $gofor = "like";
    }
    elseif($op == "unlike")
    {
        $gofor = "unlike";
    }
    else
    {
        exit;
    }
    // check if alredy liked or not query
    $query = mysqli_query($connection,"SELECT * from `likes` WHERE pid='".$pid."' and uid='".$uid."'");
    $num_rows = mysqli_num_rows($query);

    if($num_rows>0) // check if alredy liked or not condition
    {
        $likeORunlike = mysqli_fetch_array($query);
    
        if($likeORunlike['like'] == 1)  // if alredy liked set unlike for alredy liked product
        {
            mysqli_query($connection,"update `likes` set `unlike`=1,`like`=0 where id='".$likeORunlike['id']."' and uid='".$uid."'");
            echo 2;
        }
        elseif($likeORunlike['unlike'] == 1) // if alredy unliked set like for alredy unliked product
        {
            mysqli_query($connection,"update `likes` set `like`=1,`unlike`=0 where id='".$likeORunlike['id']."' and uid='".$uid."'");
            echo 2;
        }
    }
    else  // New Like
    {
       mysqli_query($connection,"INSERT INTO `likes` (`pid`,`uid`, `$gofor`) VALUES ('$pid','$uid','1')");
       echo 1;
    }
    exit;
}


$query  = "SELECT * FROM  `products`"; // products list
$res    = mysqli_query($connection,$query);
$HTML = "";
while($row=mysqli_fetch_array($res))
{
    // get likes and dislikes of a product
    $query = mysqli_query($connection,"select sum(`like`) as `like`,sum(`unlike`) as `unlike` from `likes` where pid = ".$row['id']);
    $rowCount = mysqli_fetch_array($query);
    if($rowCount['like'] == "")
        $rowCount['like'] = 0;
        
    if($rowCount['unlike'] == "")
        $rowCount['unlike'] = 0;
        
    if($uid == "") // if user not loggedin then show login link on like button click
    {
        $like = '
            <input onclick="location.href = \'login.php\';" type="button" value="'.$rowCount['like'].'" rel="'.$row['id'].'" data-toggle="tooltip"  data-placement="top" title="Login to Like" class="button_like" />
            <input onclick="location.href = \'login.php\';" type="button" value="'.$rowCount['unlike'].'" rel="'.$row['id'].'" data-toggle="tooltip" data-placement="top" title="Login to Unlike" class="button_unlike" />';
    }
    else
    {
        $query = mysqli_query($connection,"SELECT * from `likes` WHERE pid='".$row['id']."' and uid='".$uid."'");
        if(mysqli_num_rows($query)>0){ //if already liked od disliked a product
            $likeORunlike = mysqli_fetch_array($query);
            // clear values of variables
            $liked = '';
            $unliked = '';
            $disable_like = '';
            $disable_unlike = '';
            
            if($likeORunlike['like'] == 1) // if alredy liked then disable like button
            {
                $liked = 'disabled="disabled"';
                $disable_unlike = "button_disable";
            }
            elseif($likeORunlike['unlike'] == 1) // if alredy dislike the disable unlike button
            {
                $unliked = 'disabled="disabled"';
                $disable_like = "button_disable";
            }
            
            $like = '
            <input '.$liked.' type="button" value="'.$rowCount['like'].'" rel="'.$row['id'].'" data-toggle="tooltip"  data-placement="top" title="Like" class="button_like '.$disable_like.'" id="linkeBtn_'.$row['id'].'" />
            <input '.$unliked.' type="button" value="'.$rowCount['unlike'].'" rel="'.$row['id'].'" data-toggle="tooltip" data-placement="top" title="Un-Like" class="button_unlike '.$disable_unlike.'" id="unlinkeBtn_'.$row['id'].'" />
            ';
        }
        else{ //not liked and disliked product
            $like = '
            <input  type="button" value="'.$rowCount['like'].'" rel="'.$row['id'].'" data-toggle="tooltip"  data-placement="top" title="Like" class="button_like" id="linkeBtn_'.$row['id'].'" />
            <input  type="button" value="'.$rowCount['unlike'].'" rel="'.$row['id'].'" data-toggle="tooltip" data-placement="top" title="Un-Like" class="button_unlike" id="unlinkeBtn_'.$row['id'].'" />
            ';
        }
    }
        
    $HTML.='
        <li> <img src="images/'.$row['image'].'" class="">
            <h4 class="">'.$row['product_name'].'</h4>
            <div class="product-price">
                <span class="normal-price">$'.$row['price'].'</span>
            </div>
            <a href="#" class="btn btn-default navbar-btn" >Buy Now</a>
            <div class="grid">
                '.$like.'
            </div>
        </li>';
}

?>
<!doctype html>
<head>
  </head>
  <body>
   <div class="container">
    <div class="row">
    <h1>PHPGang Shopping store</h1>
        <div class="col-sm-12 col-md-12">
            <ul class="thumbnail-list">
            <?php echo $HTML; ?>
            </ul>
        </div>
    </div>
</div>
  </body>
</html>

Step 5: Create style for css.

.button_like {
    background-image: url(like.png);
    background-color: #fff;
    background-repeat: no-repeat; 
    background-position: 2px 0;
    border: none;           
    cursor: pointer;       
    height: 32px;          
    padding-left: 40px;    
    vertical-align: middle;
    color: hsl(0, 0%, 33%);
    
 
}
.button_unlike {
    background-image: url(like.png);
    background-color: #FFF;
    background-repeat: no-repeat; 
    background-position: 2px -31px;
    border: none;           
    cursor: pointer;       
    height: 32px;          
    padding-left: 40px;    
    vertical-align: middle;
    color: hsl(0, 0%, 33%);
    
 
}
.button_disable{
    background-image: url("likebw.png");
}
.grid
{
    width: 450px;
    margin: 0 auto;
    text-align:middle;
}
.thumbnail-list {
  list-style:none;
  margin:0;
  padding:0;
  font-size:0;
}
.thumbnail-list li {
  display:inline-block;
  vertical-align:top;
  width:50%;
  padding:2%;
  font-size:12px;
}
.thumbnail-list img {
  display:block;
  width:100%;
}
.item { background:green; }
.cut-price {
  text-decoration:line-through;
  color:#ccc;
}
.product-price {
  float:left;
  width:100%;
  color:#999;
}
.btn-slide { display:none; }

@media (min-width:640px) {
  .thumbnail-list li { width:33.33333%; }
}
@media (max-width:767px) {
  .btn-slide {
    text-align:center;
    width:100%;
    padding:10px;
    margin:0 auto;
    display:block;
    font:bold 120%/100% Arial,Helvetica,sans-serif;
    color:#000;
    text-decoration:none;
    border:1px solid #ccc;
  }
  #panel { display:none; }
  .thumbnail-list li { text-align:center; }
}
@media (max-width:320px) {
  .thumbnail-list li { width: 100%}
}

Add jquery code and and css link for in the code.

  <script type="text/javascript" src="jquery-1.8.0.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <link href="style.css" rel="stylesheet" type="text/css" />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

This is the simple and easy code for like and unlike system I hope you guyz like this please share your feedback in comments. If you face any issue please fee free to comment below.

Live search in PHP and Mysql using Jquery

Live search in PHP and Mysql using Jquery

This tutorials is to know how to integrate live search in php and MySQL using jquery. Searching is one of the most required feature in web sites and if it will be live searching it will show you fast result on page. In this tutorial we will create a database and a table insert records and start searching in it.

Demo       |

This is a very simple script which has 2 files. One is an HTML (index.php) file with a Search input box and the second is a PHP (do_search.php) file that has a regular MySQL connect(db.php) and a select statement to get the data from database. This script also has a Loading message shown while the data is being pulled from MySQL. Please note that live search might use more resources from your server. It might result in server overload / slowness if your infrastructure is limited.

Step1 : Setup your database and table in MySQL
Before you run this script make sure you have created a database and table in MySQL. Below is the sample sql command to create a database, table, and insert some dummy rows.

--
-- Table structure for table `live_search`
--

CREATE TABLE `live_search` (
  `id` int(10) NOT NULL,
  `name` varchar(255) NOT NULL,
  `email` varchar(100) NOT NULL,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `live_search`
--

INSERT INTO `live_search` (`id`, `name`, `email`, `date`) VALUES
(1, 'Raja', 'Raja@developerdesks.com', '2016-08-29 05:34:36'),
(2, 'Ragav', 'Ragav@developerdesks.com', '2016-08-29 05:34:36'),
(3, 'Sangeet kumar', 'sangeet@developerdesks.com', '2016-08-29 05:35:31'),
(4, 'Tharun', 'Tharun@developerdesks.com', '2016-08-29 05:35:31'),
(5, 'Kabi', 'kabi@developerdesks.com', '2016-08-29 05:35:33');

Step 2: Index page for search form. 
Create the live form for searching.

<div class="container">
<h1>Live search using php and mysql using jquery</h1>
	<div class="row">
		<div class="panel panel-default">
			<div class="panel-heading">
				<span>Live Search</span>
			</div>
			<div class="form-group">
				<label for="username">Username :</label>
				<input name="keysearch" value="" placeholder="name" id="keysearch" type="text" class="form-control">
				<span id="loading">Loading...</span>
			</div>
			<div id="result"></div>
		</div>
	</div>
</div>

Step 3: Creating a do search for getting data from database.
Create the mysql query for getting the data from table using like” options.

<?php
include('db.php');
if(isset($_POST['keysearch']))
{
    $search = $_POST['keysearch'];
    $data = mysql_query("SELECT * FROM `live_search` WHERE `name` like '%$search%' order by id LIMIT 5");
    while($row = mysql_fetch_array($data))
    {
		if($data) {
        $username   = $row['name'];
        echo "<div class='show'><img src='' id='search' /><span class='name'> $username </span></div>";
    }
	else
	{ echo "No found results";}
}
}
?>

Step 4: jquery code for get the search value and pass to do_seach page. 
Using the jquery you can get the search word and pass to the next page using variable and post method.

<script>
$(document).ready(function(){
	var req = null;
	$('#keysearch').on('keyup', function(){
		var key = $('#keysearch').val();
		if (key && key.length > 2)
		{
			$('#loading').css('display', 'block');
			if (req)
				req.abort();
			req = $.ajax({
				url : 'do_search.php',
				type : 'POST',
				cache : false,
				data : {
					keysearch : key,
				},
				success : function(data)
				{
					console.log(data)
					if (data)
					{
						$('#loading').css('display', 'none');
						$("#result").html(data).show();
					}
				}
			});
		}
		else
		{
			$('#loading').css('display', 'none');
			$('#result').css('display', 'none');
		}
 
	});
});
</script>

Step 4: Add css code fro your design.

.panel-default{padding: 15px;}
.form-group{margin-top: 15px;}
.panel-heading{background-color: #40A2BE !important; color: #FFFFFF !important;}
#loading{display: none;}
#searchid
{
    width:500px;
    border:solid 1px #000;
    padding:10px;
    font-size:14px;
}
#result
{
    position:absolute;
    width:500px;
    padding:10px;
    display:none;
    margin-top:-1px;
    border-top:0px;
    overflow:hidden;
    border:1px #CCC solid;
    background-color: white;
}
.show{font-size:20px;height: 50px;padding: 5px;}
.show:hover{background:#40A2BE;color:#FFF;cursor:pointer;}
img#search{width:50px; height:40px; float:left; margin-right:6px;}

You can now demo the script and get the live code., That’s it enjoy the code. Please subscribe. 

Creating a Side Menu Floating Using jQuery and CSS

Creating a Side Menu Floating Using jQuery and CSS

For this tutorials, We are try to create a Left Side Menu Floating Using jQuery and CSS. It means we are going to fixed the side menu while scroll the page. For the long page with contains many paragraph, readers difficult to drag up and click the next articles . so wen need to scrool the side menu it is the easy way to client for select next articles. That why we are going to do this articles

So here we go Creating a Side Menu Floating Using jQuery and CSS
Demo       |

Step 1 – HTML

  <div id="page-wrap">
	
	
		<div id="main">

		  <p>Scroll down and watch the sidebar on the right follow.</p>
		
		  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>		
		  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
		  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
		  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
		  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, commodo vitae, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis. Praesent dapibus, neque id cursus faucibus, tortor neque egestas augue, eu vulputate magna eros eu erat. Aliquam erat volutpat. Nam dui mi, tincidunt quis, accumsan porttitor, facilisis luctus, metus</p>
		
		</div>
		
		<div id="sidebar">
				
		  	<ul>
			    <li><a href="https://www.developerdesks.com/multi-select-filter-option-for-mysql-data-using-ajax/1192">Multi select filter</a></li>
			    <li><a href="https://www.developerdesks.com/file-upload-with-progress-bar-using-ajax/1647">File upload using ajax</a></li>
			    <li><a href="https://www.developerdesks.com/simple-image-overlay-title-hover-effects/1820">Image Overlay Effects css3</a></li>
			    <li><a href="https://www.developerdesks.com/30-page-preload-image-style-css/1830">30 Page Preloading</a></li>
			    <li><a href="https://www.developerdesks.com/how-to-speed-up-your-website-in-easy-way/1838">Speed Up Your Website</a></li>
			</ul>
		
		</div>
	
	</div>

Step 2 – CSS

* { margin: 0; padding: 0; }
        body { font: 14px/1.4 Georgia, serif; }
        #page-wrap { width: 600px; margin: 15px auto; }
        p { margin: 0 0 15px 0; }
        p:first-child { background: #fffcde; padding: 10px; }
        #sidebar ul { background: #eee; padding: 10px; }
        li { margin: 0 0 0 20px; }
        #main { width: 390px; float: left; }
        #sidebar { width: 190px; float: right; }

using the css, you can make scroll the left side menu.

Step 2 – jquery

<script type="text/javascript">
        $(function() {
            var offset = $("#sidebar").offset();
            var topPadding = 15;
            $(window).scroll(function() {
                if ($(window).scrollTop() > offset.top) {
                    $("#sidebar").stop().animate({
                        marginTop: $(window).scrollTop() - offset.top + topPadding
                    });
                } else {
                    $("#sidebar").stop().animate({
                        marginTop: 0
                    });
                };
            });
        });
    </script>

This above jquery is used to fixed the left side bar and make the left side menu scroll. This is simple code and enjoy it.