Skip to main content

Follow and Unfollow System with PHP & MySQL

In our previous tutorial, we have developed a GST Billing System with PHP and MySQL. In this tutorial, we will explain how to develop Follow and Unfollow System with PHP and MySQL.

We are familiar with the follow and follow functionality as it is used in social networking applications such Twitter, Linkedin etc. In follow and unfollow system, user follow other users to interact them to view their details, posts etc. The users are unfollowed when a user don’t want to interact with them.

Also, read:

So here in this tutorial, we will develop follow and unfollow system to allow users to follow/unfollow users, share posts and like posts. This is very useful initial level project to develop your own social networking system. You can enhance it to allow comment, share, and delete features.

Here in this tutorial, we will cover following features.

  • User login.
  • Follow / Unfollow user.
  • List followers.
  • List following.
  • Post messages.
  • Display messages.
  • Like/Unlike message.

So let’s implement online billing system. The major files are:

  • login.php
  • index.php
  • profile.php
  • following.php
  • follower.php
  • User.php: User class to hold methods related to user.
  • Post.php: Post class to hold methods related to posts.

Step1: Create MySQL Database Table

First we will create database tables for our system. We will create table social_user to store user details.

CREATE TABLE `social_user` (
  `user_id` int(11) NOT NULL,
  `username` varchar(255) NOT NULL,
  `email` varchar(150) NOT NULL,
  `password` varchar(150) NOT NULL,
  `name` varchar(150) NOT NULL,
  `profile_image` varchar(150) NOT NULL,
  `bio` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

we will create table social_follow to store user follow details.

CREATE TABLE `social_follow` (
  `follow_id` int(11) NOT NULL,
  `follower_id` int(11) NOT NULL,
  `followed_user_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

we will create table social_post to store user’s post details.

CREATE TABLE `social_post` (
  `post_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `content` text CHARACTER SET utf8 NOT NULL,
  `created` datetime NOT NULL DEFAULT current_timestamp()
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

and we will create table social_like to store user post like details.

CREATE TABLE `social_like` (
  `like_id` int(11) NOT NULL,
  `user_id` int(11) NOT NULL,
  `post_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Step2: Implement User Follow and Unfollow

We will display users with follow button and implement user follow functionality.

<div class="card-body">
	<?php 
	$unfollowedUserResult = $user->getFollower();
	while ($unfollowedUser = $unfollowedUserResult->fetch_assoc()) { 	
	?>					
	<li class="list-group-item" style="padding:5px;">					
		<a href="#"><img src="images/<?php echo $unfollowedUser['profile_image']; ?>" width="50"/>@<?php echo $unfollowedUser['username']; ?></a> 
		<button type="button" id="follow_<?php echo $unfollowedUser['user_id']; ?>" data-userid="<?php echo $unfollowedUser['user_id']; ?>" class="btn btn-primary pull-right follow" style="margin:5px 5px 0px 0px;">Follow</button>
	</li>					
	<?php } ?>					
</div>

we will handle user follow functionality by making ajax request to user_action.php with action followUser and update details.

$(document).on('click', '.follow', function(){
	var userId = $(this).data("userid");		
	var action = 'followUser';
	$.ajax({
		url:'user_action.php',
		method:"POST",
		data:{userId:userId, action:action},
		dataType:"json",
		success:function(response){				
			if(response.success == 1) {
				$("#follow_"+userId).text("Following");
				$("#following").text(parseInt($("#following").text()) + 1);
			}					
		}
	});
});

In user_action.php, we will check for action followUser and call method followUser() from class User.php.

if(!empty($_POST['action']) && $_POST['action'] == 'followUser') {
	$user->followUserId = $_POST["userId"];	
	$user->followUser();
}

We will implement method followUser() in class User.php to follow user.

public function followUser() {
	if($_SESSION["user_id"] && $this->followUserId) {			
		$sqlQuery = "INSERT INTO ".$this->followTable."(`follower_id`, `followed_user_id`)
			VALUES(?, ?)";					
		$stmt = $this->conn->prepare($sqlQuery);						
		$stmt->bind_param("ii", $_SESSION["user_id"], $this->followUserId);	
		if($stmt->execute()){				
			$output = array(			
				"success"	=> 	1
			);
			echo json_encode($output);
		}
	}		
}

Step3: Implement Post Message and Share

We will create form with textarea and share button to post and share messages.

<form method="post" id="postForm">
	<div class="tab-content" id="myTabContent">
		<div class="tab-pane fade show active" id="posts" role="tabpanel" aria-labelledby="posts-tab">
			<div class="form-group">
				<label class="sr-only" for="message">post</label>
				<textarea class="form-control" id="message" name="message" rows="3" placeholder="What are you thinking?"></textarea>
			</div>

		</div>						
	</div>
	<div class="btn-toolbar justify-content-between">
		<div class="btn-group">
			<input type="hidden" name="action" id="action" value="" />
			<button type="submit" id="postShareButton" class="btn btn-primary">share</button>
		</div>						
	</div>
</form>

We will handle post form submit with jQuery and then make Ajax request to user_action.php with action addPost to post message.

$("#postSection").on('submit','#postForm', function(event){
	event.preventDefault();
	$('#save').attr('disabled','disabled');
	$('#action').val('addPost');
	var formData = $(this).serialize();
	$.ajax({
		url:"user_action.php",
		method:"POST",
		data:formData,
		success:function(data){				
			$('#postForm')[0].reset();							
			$('#postShareButton').attr('disabled', false);
			location.reload();				
		}
	});		
});		

we will check for action addPost in user_action.php and call method insert() from class Post.php.

if(!empty($_POST['action']) && $_POST['action'] == 'addPost') {
	$post->message = $_POST["message"];	
	$post->insert();
}

Now we will implement method insert() in class Post.php to insert message and display it.

public function insert(){		
	if($this->message && $_SESSION["user_id"]) {

		$stmt = $this->conn->prepare("
			INSERT INTO ".$this->postTable."(`user_id`, `content`)
			VALUES(?, ?)");
	
		$this->message = htmlspecialchars(strip_tags($this->message));
					
		$stmt->bind_param("is", $_SESSION["user_id"], $this->message);
		
		if($stmt->execute()){
			return true;
		}		
	}
}

Step4: Implement Message Listing

We will call method getFollowedUserPosts() from class Post.php to list posts.

<?php
$userPostResults = $post->getFollowedUserPosts();
while ($post = $userPostResults->fetch_assoc()) {
$date=date_create($post['created']);			
$isPostLiked = $user->getUserPostLike($post["post_id"]);
?>			
<div class="card gedf-card">
	<div class="card-header">
		<div class="d-flex justify-content-between align-items-center">
			<div class="d-flex justify-content-between align-items-center">
				<div class="mr-2">
					<img class="rounded-circle" width="45" src="images/<?php echo $post['profile_image']; ?>" alt="">
				</div>
				<div class="ml-2">
					<div class="h5 m-0">@<?php echo $post['username']; ?></div>
					<div class="h7 text-muted"><?php echo $post['name']; ?></div>
				</div>
			</div>							
		</div>
	</div>
	<div class="card-body">
		<div class="text-muted h7 mb-2"> <i class="fa fa-clock-o"></i> <?php echo date_format($date,"d/m/Y H:i:s"); ?></div>
		<p class="card-text">
			<?php echo $post['content']; ?>
		</p>
	</div>
	<div class="card-footer">
		<a class="card-link <?php IF ($isPostLiked) { echo "dislikePost"; } else { echo "likePost";}?>" id="like_<?php echo  $post['post_id']; ?>" data-post-id="<?php echo $post['post_id']; ?>">
		<i title="<?php IF ($isPostLiked) { echo "Liked"; } else { echo "Like";}?>" id="likeIcon_<?php echo  $post['post_id']; ?>"class="<?php IF ($isPostLiked) { echo "fa fa-thumbs-down"; } else { echo "fa fa-thumbs-up";}?>"></i></a>					
	</div>
</div>			
<?php }  ?>

Now we will implement method getFollowedUserPosts() in class Post.php to get posts to list.

public function getFollowedUserPosts(){	
	if(!empty($_SESSION["user_id"])) {
		
		$sqlFollowedQuery = "SELECT follow.followed_user_id FROM ".$this->followTable." AS follow WHERE follow.follower_id = '".$_SESSION["user_id"]."'";
		$followedStmt = $this->conn->prepare($sqlFollowedQuery);
		$followedStmt->execute();			
		$followedResult = $followedStmt->get_result();	
		$userIds = '';
		while ($user = $followedResult->fetch_assoc()) { 			
		 $userIds .= $user['followed_user_id'].",";
		}
		$userIds = chop($userIds,",");
		if($userIds) {
			$userIds.= ",";
		}
		$userIds.= $_SESSION["user_id"];			
		$sqlQuery = "
			SELECT user.user_id, user.username, user.name, user.profile_image, post.content, post.post_id, post.created
			FROM ".$this->userTable." AS user
			LEFT JOIN ".$this->postTable." AS post ON user.user_id = post.user_id			
			WHERE user.user_id IN ($userIds) ORDER BY post.created DESC";
		$stmt = $this->conn->prepare($sqlQuery);
		$stmt->execute();			
		$result = $stmt->get_result();		
		return $result;	
	}
}

Step5: Implement Post Like and Unlike

We will make ajax request with action likePost to handle post like.

$(document).on('click', '.likePost', function(){
	var postId = $(this).data("post-id");
	var action = 'likePost';
	$.ajax({
		url:'user_action.php',
		method:"POST",
		data:{postId:postId, action:action},
		dataType:"json",
		success:function(response){				
			if(response.success == 1) {
				$("#like_"+postId).removeClass('likePost').addClass('dislikePost');
				$("#likeIcon_"+postId).removeClass('fa fa-thumbs-up').addClass('fa fa-thumbs-down').attr("title", "Liked");					
			}					
		}
	});
});

We will check for action likePost and call method likePost() in class Post.php handle post like.

if(!empty($_POST['action']) && $_POST['action'] == 'likePost') {
	$post->postId = $_POST["postId"];	
	$post->likePost();
}

and we will implement likePost() method to insert post like functionality.

public function likePost(){		
	if($this->postId && $_SESSION["user_id"]) {

		$stmt = $this->conn->prepare("
			INSERT INTO ".$this->likeTable."(`user_id`, `post_id`)
			VALUES(?, ?)");
	
		$this->postId = htmlspecialchars(strip_tags($this->postId));
					
		$stmt->bind_param("is", $_SESSION["user_id"], $this->postId);
		
		if($stmt->execute()){
			$output = array(			
				"success"	=> 	1
			);
			echo json_encode($output);
		}		
	}
}

You may also like:

You can view the live demo from the Demo link and can download the source from the Download link below.
Demo Download

4 thoughts on “Follow and Unfollow System with PHP & MySQL

  1. you can check code in user login function and make required changes. thanks!

  2. Hello there!!

    Im having 2 issues:
    1. When I hit link to follower.php it takes me back to login page. How do I fix it so that this and the following.php page will work correctly?

    2. Got this error:
    You might like

    Fatal error: Uncaught Error: Call to a member function getUnfollowedUsers() on null in /homepages/23/d815730660/htdocs/pro.php:217 Stack trace: #0 {main} thrown in /homepages/23/d815730660/htdocs/pro.php on line 217

    Line 217:
    $unfollowedUserResult = $user->getUnfollowedUsers();
    How do I fix this?

    Thank ya so very much!!!

  3. I have checked and it’s working fine demo. Please provide source code and tables to check at my end. Thanks!

Comments are closed.