Monday, 7 January 2019

Twitter Like Follow Unfollow System in PHP using Ajax jQuery



From this post, you can learn how to make Follow and Unfollow system like Twitter which you can create in PHP using Ajax jQuery Mysql and Bootstrap. There are many viewers has requested to use PHP to build a Twitter like system. If you know on Twitter can post short News in Tweets format, and that tweets will be visible to those Twitter user who has follow this share user. When user share any news or tweets, that will be visible to his followers. So, this type of system we will make in PHP using Ajax jQuery and Mysql Database.

IF you are looking for any Social Networking Application for you colleage project, Then this post will help you to make small Follow Unfollow Application in PHP using Ajax step by step. On every publish of video tutorial of this post, you can find updated source code under this post. So, here we will show you How to develop twitter like follow and Unfollow system using Ajax in PHP script. Because most of this Social Networking sites are make in PHP Ajax. Here we have also use Bootstrap library for CSS purpose for make this system. So, here we will make dynamic follow unfollow application in PHP using Ajax.

Following are the main functionality of this follow unfollow system.

  • New User Registration
  • Login form for registered user
  • Authenticated User can edit his or here profile with upload profile image
  • User can share post, and list post
  • List User with follow unfollow button
  • Display number of followers of each user
  • Main functionality is to follow or unfollow other user post
  • Display dynamic results will be display if user click on follow unfollo button
  • All data will display using Ajax without refresh of web page
  • If you user follow any user, then he can also unfollow that user again

So, Above are the main functionality of this follow unfollow system in PHP using Ajax jQuery Mysql and Bootstrap. Below you can find source code of Ajax based follow unfollow system.



Video Tutorial


Part 1




Part 2




Part 3




Part 4




Part 5




Part 6




Part 7




Part 8




Source Code


Database


Run follow SQL script, it will make three table like tbl_twitter_user, tbl_samples_post and tbl_follow in your PHPMysqmin. Follow Unfollow system has been use this three table for make application.


CREATE TABLE `tbl_follow` (
  `follow_id` int(11) NOT NULL AUTO_INCREMENT,
  `sender_id` int(11) NOT NULL,
  `receiver_id` int(11) NOT NULL,
  PRIMARY KEY (`follow_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_samples_post` (
  `post_id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) NOT NULL,
  `post_content` text NOT NULL,
  `post_datetime` datetime NOT NULL,
  PRIMARY KEY (`post_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_twitter_user` (
  `user_id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `name` varchar(150) NOT NULL,
  `profile_image` varchar(150) NOT NULL,
  `bio` text NOT NULL,
  `follower_number` int(11) NOT NULL,
  PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

CREATE TABLE `tbl_comment` (
  `comment_id` int(11) NOT NULL AUTO_INCREMENT,
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `comment` text NOT NULL,
  `timestamp` datetime NOT NULL,
  PRIMARY KEY (`comment_id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;



database_connection.php


This PHP file is used for make database connection. This is common file which we will used in all files for make Mysql Database connection.


<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");

?>







register.php


For any dynamic web application, we have to first make register form. So, here also first we want to make user registration system. So, new user can register into system. So, for make any dynamic system, here we have make this register form. In this system, here we have validate username already exists or not. If username already exists then user cannot register into system. In this registration system we have also validate user password by re-entering password. So, this is basic validation, which we have use here for make registration system for Follow Unfollow system using PHP with Ajax jQuery Mysql and Bootstrap.


<!--
//register.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST['register']))
{
 $username = trim($_POST["username"]);
 $password = trim($_POST["password"]);
 $check_query = "
 SELECT * FROM tbl_twitter_user 
 WHERE username = :username
 ";
 $statement = $connect->prepare($check_query);
 $check_data = array(
  ':username'  => $username
 );
 if($statement->execute($check_data))
 {
  if($statement->rowCount() > 0)
  {
   $message .= '<p><label>Username already taken</label></p>';
  }
  else
  {
   if(empty($username))
   {
    $message .= '<p><label>Username is required</label></p>';
   }
   if(empty($password))
   {
    $message .= '<p><label>Password is required</label></p>';
   }
   else
   {
    if($password != $_POST["confirm_password"])
    {
     $message .= '<p><label>Password not match</label></p>';
    }
   }
   if($message == '')
   {
    $data = array(
     ':username'  => $username,
     ':password'  => password_hash($password, PASSWORD_DEFAULT)
    );

    $query = "
    INSERT INTO tbl_twitter_user 
    (username, password) 
    VALUES (:username, :password)
    ";

    $statement = $connect->prepare($query);

    if($statement->execute($data))
    {
     $message = '<label>Registration Completed</label>';
    }
   }
  }
 }
}

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Twitter Like Follow Unfollow System in PHP using Ajax jQuery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Register</div>
    <div class="panel-body">
     <form method="post">
      <span class="text-danger"><?php echo $message; ?></span>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" id="password" class="form-control" />
      </div>
      <div class="form-group">
       <label>Re-enter Password</label>
       <input type="password" name="confirm_password" id="confirm_password" class="form-control" />
      </div>
      <div class="form-group">
       <input type="submit" name="register" class="btn btn-info" value="Register" />
      </div>
      <div align="center">
       <a href="login.php">Login</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


login.php


Once you have make registration system in Follow Unfollow application. After registration you have to make login page for authenticate user login details like username and password. Here password will be validate by using password_hash() method. Because at the time registration we have store password in hash format. If user has enter proper details, then his for validate user is login or not in whole system, we have store user details under $_SESSION variable.


<!--
//login.php
!-->

<?php

include('database_connection.php');

session_start();

$message = '';

if(isset($_SESSION['user_id']))
{
 header('location:index.php');
}

if(isset($_POST["login"]))
{
 $query = "
 SELECT * FROM tbl_twitter_user 
    WHERE username = :username
 ";
 $statement = $connect->prepare($query);
 $statement->execute(
  array(
      ':username' => $_POST["username"]
     )
 );
 $count = $statement->rowCount();
 if($count > 0)
 {
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   if(password_verify($_POST['password'], $row['password']))
   {
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['username'] = $row['username'];
    header('location:index.php');
   }
   else
   {
    $message = '<label>Wrong Password</label>';
   }
  }
 }
 else
 {
  $message = '<label>Wrong Username</labe>';
 }
}


?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>  
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    </head>  
    <body>  
        <div class="container">
   <br />
   
   <h3 align="center">Twitter Like Follow Unfollow System in PHP using Ajax jQuery</a></h3><br />
   <br />
   <div class="panel panel-default">
      <div class="panel-heading">Login</div>
    <div class="panel-body">
     <form method="post">
      <p class="text-danger"><?php echo $message; ?></p>
      <div class="form-group">
       <label>Enter Username</label>
       <input type="text" name="username" class="form-control" required />
      </div>
      <div class="form-group">
       <label>Enter Password</label>
       <input type="password" name="password" class="form-control" required />
      </div>
      <div class="form-group">
       <input type="submit" name="login" class="btn btn-info" value="Login" />
      </div>
      <div align="center">
       <a href="register.php">Register</a>
      </div>
     </form>
    </div>
   </div>
  </div>
    </body>  
</html>


index.php


If system is validated user information, and it is correct then page will be redirect to index.php page. From this page user can share his or her post. User can view his or her post along with post of follow user by login user. On index page user can view all user list with follow and unfollow button. Most of all operation of follow and unfollow system will be done on this page. This page will be view to only login user.


<!--
//index.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
    header('location:login.php');
}

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <?php
            include('menu.php');
            ?>
            <div class="row">
                <div class="col-md-8">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">Start Write Here</h3>
                        </div>
                        <div class="panel-body">
                            <form method="post" id="post_form">
                                <div class="form-group">
                                    <textarea name="post_content" id="post_content" maxlength="160" class="form-control" placeholder="Write your short story"></textarea>
                                </div>
                                <div class="form-group">
                                    <input type="hidden" name="action" value="insert" />
                                    <input type="submit" name="share_post" id="share_post" class="btn btn-primary" value="Share" />
                                </div>
                            </form>
                        </div>
                    </div>
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">Trending Now</h3>
                        </div>
                        <div class="panel-body">
                            <div id="post_list">

                            </div>
                        </div>
                    </div>
                </div>
                <div class="col-md-4">
                    <div class="panel panel-default">
                        <div class="panel-heading">
                            <h3 class="panel-title">User List</h3>
                        </div>
                        <div class="panel-body">
                            <div id="user_list"></div>
                        </div>
                    </div>
                </div>
            </div>
  </div>
    </body>  
</html>

<script>  
$(document).ready(function(){
 
 $('#post_form').on('submit', function(event){
        event.preventDefault();
        if($('#post_content').val() == '')
        {
            alert('Enter Story Content');
        }
        else
        {
            var form_data = $(this).serialize();
            $.ajax({
                url:"action.php",
                method:"POST",
                data:form_data,
                success:function(data)
                {
                    alert('Post has been shared');
                    $('#post_form')[0].reset();
                    fetch_post();
                }
            })
        }
    });

    fetch_post();

    function fetch_post()
    {
       var action = 'fetch_post';
       $.ajax({
            url:'action.php',
            method:"POST",
            data:{action:action},
            success:function(data)
            {
                $('#post_list').html(data);
            }
       })
    }

    fetch_user();

    function fetch_user()
    {
        var action = 'fetch_user';
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{action:action},
            success:function(data)
            {
                $('#user_list').html(data);
            }
        });
    }

    $(document).on('click', '.action_button', function(){
        var sender_id = $(this).data('sender_id');
        var action = $(this).data('action');
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{sender_id:sender_id, action:action},
            success:function(data)
            {
                fetch_user();
                fetch_post();
            }
        })
    });

    var post_id;
    var user_id;

    $(document).on('click', '.post_comment', function(){
        post_id = $(this).attr('id');
        user_id = $(this).data('user_id');
        var action = 'fetch_comment';
        $.ajax({
            url:"action.php",
            method:"POST",
            data:{post_id:post_id, user_id:user_id, action:action},
            success:function(data){
                $('#old_comment'+post_id).html(data);
                $('#comment_form'+post_id).slideToggle('slow');
            }
        })
        
    });

    $(document).on('click', '.submit_comment', function(){
        var comment = $('#comment'+post_id).val();
        var action = 'submit_comment';
        var receiver_id = user_id;
        if(comment != '')
        {
            $.ajax({
                url:"action.php",
                method:"POST",
                data:{post_id:post_id,receiver_id:receiver_id,comment:comment,action:action},
                success:function(data)
                {
                    $('#comment_form'+post_id).slideUp('slow');
                    fetch_post();
                }
            })
        }
    });
 
});  
</script>


menu.php


This file is used for make dynamic menu, here user name will be display by using $_SESSION varibale. Here in this we have add two menu for go to profile page and logout page.


                        <br />
   <nav class="navbar navbar-inverse">
    <div class="container-fluid">
     <div class="navbar-header">
      <a class="navbar-brand" href="index.php">Webslesson</a>
     </div>
     <ul class="nav navbar-nav navbar-right">
      <li class="dropdown">
       <a class="dropdown-toggle" data-toggle="dropdown" href="#"><?php echo $_SESSION['username']; ?>
       <span class="caret"></span></a>
       <ul class="dropdown-menu">
        <li><a href="profile.php">Profile</a></li>
        <li><a href="logout.php">Logout</a></li>
       </ul>
      </li>
     </ul>
    </div>
   </nav>


logout.php


If user want to logout from dynamic follow unfollow application, so when user click on logout link then page will redirect to this page, and on this page all $_SESSION variable will be destroy using session_destroy() function.


<?php

//logout.php

session_start();

session_destroy();

header('location:login.php');

?>


profile.php


This file is used for edit user profile details in follow unfollow application by using PHP. Here user not only edit their profile details like username, password, name and short bio but also user can change profile image by upload image file under images folder. This image and user name will be display to other user.


<!--
//profile.php
!-->

<?php

include('database_connection.php');

session_start();

if(!isset($_SESSION['user_id']))
{
 header('location:login.php');
}

$message = '';

if(isset($_POST['edit_profile']))
{
 $file_name = '';
 if(isset($_POST['profile_image']))
 {
  $file_name = $_POST['profile_image'];
 }

 if($_FILES['profile_image']['name'] != '')
 {
  if($file_name != '')
  {
   unlink('images/'.$file_name);
  }
  $image_name = explode(".", $_FILES['profile_image']['name']);
  $extension = end($image_name);
  $temporary_location = $_FILES['profile_image']['tmp_name'];
  $file_name = rand() . '.' . strtolower($extension);
  $location = 'images/' . $file_name;
  move_uploaded_file($temporary_location, $location);
 }
 $check_query = "
 SELECT * FROM tbl_twitter_user WHERE username = :username AND user_id != :user_id
 ";
 $statement = $connect->prepare($check_query);
 $statement->execute(
  array(
   ':username'  =>  trim($_POST["username"]),
   ':user_id'  =>  $_SESSION["user_id"]
  )
 );
 $total_row = $statement->rowCount();
 if($total_row > 0)
 {
  $message = '<div class="alert alert-danger">Username Already Exists</div>';
 }
 else
 {
  $data = array(
   ':username'   => trim($_POST["username"]),
   ':name'    => trim($_POST["name"]),
   ':profile_image' => $file_name,
   ':bio'    => trim($_POST["bio"]),
   ':user_id'   => $_SESSION["user_id"]
  );
  if($_POST['password'] != '')
  {
   $data[] = array(
    ':password'  => password_hash($_POST["password"], PASSWORD_DEFAULT)
   );
   $query = '
   UPDATE tbl_twitter_user SET username = :username, password = :password, name = :name, profile_image = :profile_image, bio = :bio WHERE user_id = :user_id
   ';
  }
  else
  {
   $query = '
   UPDATE tbl_twitter_user SET username = :username, name = :name, profile_image = :profile_image, bio = :bio WHERE user_id = :user_id
   ';
  }
  $statement = $connect->prepare($query);
  if($statement->execute($data))
  {
   $message = '<div class="alert alert-success">Profile Updated</div>';
  }
 }
}



$query = "SELECT * FROM tbl_twitter_user WHERE user_id = '".$_SESSION["user_id"]."'";

$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

?>

<html>  
    <head>  
        <title>Twitter Like Follow Unfollow System in PHP using Ajax jQuery</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.2.2/jquery.form.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>  
    <body>  
        <div class="container">
   <?php 
   include('menu.php');
   ?>
   <div class="row">
    <div class="col-md-3">
    
    </div>
    <div class="col-md-6">
     <div class="panel panel-default">
      <div class="panel-heading">
       <h3 class="panel-title">Edit Profile</h3>
      </div>
      <div class="panel-body">
       <?php
       foreach($result as $row)
       {
        echo $message;
       ?>
       <form method="post" enctype="multipart/form-data">
        <div class="form-group">
         <label>Username</label>
         <input type="text" name="username" id="username" pattern="^[a-zA-Z0-9_.-]*$" required class="form-control" value="<?php echo $row["username"];?>" />
        </div>
        <div class="form-group">
         <label>Password</label>
         <input type="password" name="password" id="password" class="form-control" />
        </div>
        <div class="form-group">
         <label>Name</label>
         <input type="text" name="name" id="name" class="form-control" required value="<?php echo $row["name"]; ?>" />
        </div>
        <div class="form-group">
         <label>Profile Image</label>
         <input type="file" name="profile_image" id="profile_image" accept="image/*" />
         <?php
         if($row["profile_image"] != '')
         {
          echo '<img src="images/'.$row["profile_image"].'" class="img-thumbnail" width="150" />';
          echo '<input type="hidden" name="profile_image" value="'.$row["profile_image"].'" />';
         }
         ?>
        </div>
        <div class="form-group">
         <label>Short Bio</label>
         <textarea name="bio" id="bio" class="form-control"><?php echo $row["bio"]; ?></textarea>
        </div>
        <div class="form-group">
         <input type="submit" name="edit_profile" id="edit_profile" class="btn btn-primary" value="Save" />
        </div>
       </form>
       <?php
       }
       ?>
      </div>
     </div>
    </div>
    <div class="col-md-3">
    
    </div>
   </div>
  </div>
    </body>  
</html>


action.php


This file is used for perform all core operation of Insert Post, Fetch post data, fetch user data and make follow unfollow button in PHP Follow Unfollow system. This file will received request for all above operation.


<?php

//action.php

include('database_connection.php');

session_start();

if(isset($_POST['action']))
{
 $output = '';
 if($_POST['action'] == 'insert')
 {
  $data = array(
   ':user_id'   => $_SESSION["user_id"],
   ':post_content'  => $_POST["post_content"],
   ':post_datetime' => date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')))
  );
  $query = "
  INSERT INTO tbl_samples_post 
  (user_id, post_content, post_datetime) 
  VALUES (:user_id, :post_content, :post_datetime)
  ";

  $statement = $connect->prepare($query);
  $statement->execute($data);
 }

 if($_POST['action'] == 'fetch_post')
 {
  $query = "
  SELECT * FROM tbl_samples_post 
  INNER JOIN tbl_twitter_user ON tbl_twitter_user.user_id = tbl_samples_post.user_id 
  LEFT JOIN tbl_follow ON tbl_follow.sender_id = tbl_samples_post.user_id 
  WHERE tbl_follow.receiver_id = '".$_SESSION["user_id"]."' OR tbl_samples_post.user_id = '".$_SESSION["user_id"]."' 
  GROUP BY tbl_samples_post.post_id 
  ORDER BY tbl_samples_post.post_id DESC
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  $total_row = $statement->rowCount();
  if($total_row > 0)
  {
   foreach($result as $row)
   {
    $profile_image = '';
    if($row['profile_image'] != '')
    {
     $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive" />';
    }
    else
    {
     $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive" />';
    }
    $output .= '
    <div class="jumbotron" style="padding:24px 30px 24px 30px">
     <div class="row">
      <div class="col-md-2">
       '.$profile_image.'
      </div>
      <div class="col-md-8">
       <h3><b>@'.$row["username"].'</b></h3>
       <p>'.$row["post_content"].'
       <button type="button" class="btn btn-link post_comment" id="'.$row["post_id"].'" data-user_id="'.$row["user_id"].'">'.count_comment($connect, $row["post_id"]).' Comment</button>
       </p>
       <div id="comment_form'.$row["post_id"].'" style="display:none;">
        <span id="old_comment'.$row["post_id"].'"></span>
        <div class="form-group">
         <textarea name="comment" class="form-control" id="comment'.$row["post_id"].'"></textarea>
        </div>
        <div class="form-group" align="right">
         <button type="button" name="submit_comment" class="btn btn-primary btn-xs submit_comment">Comment</button>
        </div>
       </div>
      </div>
     </div>
    </div>
    ';
   }
  }
  else
  {
   $output = '<h4>No Post Found</h4>';
  }
  echo $output;
 }
 if($_POST['action'] == 'fetch_user')
 {
  $query = "
  SELECT * FROM tbl_twitter_user 
  WHERE user_id != '".$_SESSION["user_id"]."' 
  ORDER BY user_id DESC
  ";
  $statement = $connect->prepare($query);
  $statement->execute();
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $profile_image = '';
   if($row['profile_image'] != '')
   {
    $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive" />';
   }
   else
   {
    $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive" />';
   }
   $output .= '
   <div class="row">
    <div class="col-md-4">
     '.$profile_image.'
    </div>
    <div class="col-md-8">
     <h4><b>@'.$row["username"].'</b></h4>
     '.make_follow_button($connect, $row["user_id"], $_SESSION["user_id"]).'
     <span class="label label-success"> '.$row["follower_number"].' Followers</span>
    </div>
   </div>
   <hr />
   ';
  }
  echo $output;
 }

 if($_POST['action'] == 'follow')
 {
  $query = "
  INSERT INTO tbl_follow 
  (sender_id, receiver_id) 
  VALUES ('".$_POST["sender_id"]."', '".$_SESSION["user_id"]."')
  ";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $sub_query = "
   UPDATE tbl_twitter_user SET follower_number = follower_number + 1 WHERE user_id = '".$_POST["sender_id"]."'
   ";
   $statement = $connect->prepare($sub_query);
   $statement->execute();
  }

 }

 if($_POST['action'] == 'unfollow')
 {
  $query = "
  DELETE FROM tbl_follow 
  WHERE sender_id = '".$_POST["sender_id"]."' 
  AND receiver_id = '".$_SESSION["user_id"]."'
  ";
  $statement = $connect->prepare($query);
  if($statement->execute())
  {
   $sub_query = "
   UPDATE tbl_twitter_user 
   SET follower_number = follower_number - 1 
   WHERE user_id = '".$_POST["sender_id"]."'
   ";
   $statement = $connect->prepare($sub_query);
   $statement->execute();
  }
 }

 if($_POST["action"] == 'submit_comment')
 {
  $data = array(
   ':post_id'  => $_POST["post_id"],
   ':user_id'  => $_SESSION["user_id"],
   ':comment'  => $_POST["comment"],
   ':timestamp' => date("Y-m-d") . ' ' . date("H:i:s", STRTOTIME(date('h:i:sa')))
  );
  $query = "
  INSERT INTO tbl_comment 
  (post_id, user_id, comment, timestamp) 
  VALUES (:post_id, :user_id, :comment, :timestamp)
  ";
  $statement = $connect->prepare($query);
  $statement->execute($data);

 }
 if($_POST["action"] == "fetch_comment")
 {
  $query = "
  SELECT * FROM tbl_comment 
  INNER JOIN tbl_twitter_user 
  ON tbl_twitter_user.user_id = tbl_comment.user_id 
  WHERE post_id = '".$_POST["post_id"]."' 
  ORDER BY comment_id ASC
  ";
  $statement = $connect->prepare($query);
  $output = '';
  if($statement->execute())
  {
   $result = $statement->fetchAll();
   foreach($result as $row)
   {
    $profile_image = '';
    if($row['profile_image'] != '')
    {
     $profile_image = '<img src="images/'.$row["profile_image"].'" class="img-thumbnail img-responsive img-circle" />';
    }
    else
    {
     $profile_image = '<img src="images/user.jpg" class="img-thumbnail img-responsive img-circle" />';
    }
    $output .= '
    <div class="row">
     <div class="col-md-2">
     '.$profile_image.' 
     </div>
     <div class="col-md-10" style="margin-top:16px; padding-left:0">
      <small><b>@'.$row["username"].'</b><br />
      '.$row["comment"].'
      </small>
     </div>
    </div>
    <br />
    ';
   }
  }
  echo $output;
 }
}

function count_comment($connect, $post_id)
{
 $query = "
 SELECT * FROM tbl_comment 
 WHERE post_id = '".$post_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 return $statement->rowCount();
}

function make_follow_button($connect, $sender_id, $receiver_id)
{
 $query = "
 SELECT * FROM tbl_follow 
 WHERE sender_id = '".$sender_id."' 
 AND receiver_id = '".$receiver_id."'
 ";
 $statement = $connect->prepare($query);
 $statement->execute();
 $total_row = $statement->rowCount();
 $output = '';
 if($total_row > 0)
 {
  $output = '<button type="button" name="follow_button" class="btn btn-warning action_button" data-action="unfollow" data-sender_id="'.$sender_id.'"> Following</button>';
 }
 else
 {
  $output = '<button type="button" name="follow_button" class="btn btn-info action_button" data-action="follow" data-sender_id="'.$sender_id.'"><i class="glyphicon glyphicon-plus"></i> Follow</button>';
 }
 return $output;
}




?>


Remaining source code will be added very shortly.



7 comments:

  1. Thanks pls I need php code for students result check
    Email: raphaelugonna@gmail.com

    ReplyDelete
  2. Trending Now

    Notice: Array to string conversion in C:\xampp\htdocs\tutorial\Twitter Like Follow Unfollow System in PHP using Ajax jQuery\action.php on line 17
    No Post Found

    ReplyDelete
  3. Trending Now

    Notice: Array to string conversion in C:\xampp\htdocs\tutorial\Twitter Like Follow Unfollow System in PHP using Ajax jQuery\action.php on line 17
    No Post Found this is my problem what happend i do

    ReplyDelete
  4. Please can help me this, i'm stock
    Warning: include(database_connection.php): failed to open stream: No such file or directory in /opt/lampp/htdocs/followers/register.php on line 7

    Warning: include(): Failed opening 'database_connection.php' for inclusion (include_path='.:/opt/lampp/lib/php') in /opt/lampp/htdocs/followers/register.php on line 7

    Notice: Undefined variable: connect in /opt/lampp/htdocs/followers/register.php on line 26

    Fatal error: Uncaught Error: Call to a member function prepare() on null in /opt/lampp/htdocs/followers/register.php:26 Stack trace: #0 {main} thrown in /opt/lampp/htdocs/followers/register.php on line 26

    ReplyDelete
  5. SELECT * FROM tbl_samples_post
    LEFT JOIN tbl_twitter_user ON tbl_twitter_user.user_id = tbl_samples_post.user_id
    WHERE tbl_samples_post.user_id = '".$_SESSION["user_id"]."'
    GROUP BY tbl_samples_post.post_id
    ORDER BY post_id DESC";


    WHERE tbl_samples_post.user_id = '".$_SESSION["user_id"]."'

    I am getting errors in this field

    ReplyDelete