Facebook / Twitter style mention system with PHP is one of the cool implementation in the social networks. It is used to mention the particular user by adding @ symbol infront of the username. When you start typing @ followed by username, social networks automattically suggests the users via autocomplete search box. We have to select the user from the dropdown, thats it.

So the system automatically identify the user  by using @username and send a notification to them. In this post I have explained how to implement PHP mention system with fetching, parsing and storing the data in the database.

In my previous post I had explained about hashtag system with PHP you can also integrate both hashtag & mention script together in your web application.

Facebook Twitter Style Mention System with PHP, jQuery & PDO
Facebook Twitter Style Mention System with PHP, jQuery & PDO

Database Design for Mention System with PHP

To build a Mention System with PHP, you have to create two tables such as  Users  &  Posts . You can do it from phpmyadmin

Users Table

This table contains all the users details like id, name, email, status and profile picture url.

CREATE TABLE `users` (
 `user_id` int(9) NOT NULL PRIMARY AUTO_INCREMENT,
 `user_name` varchar(20) NOT NULL UNIQUE,
 `user_email` varchar(30) NOT NULL,
 `user_profile_url` varchar(200) NOT NULL,
 `user_status` smallint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

I have loaded with sample datas as below

PHP Mention System - Users Table

Posts Table

This table contains user’s post message data, date and who posted it

CREATE TABLE `posts` (
 `post_id` int(9) NOT NULL PRIMARY AUTO_INCREMENT,
 `post_text` mediumtext NOT NULL,
 `post_user_id` int(9) NOT NULL,
 `post_date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

 

This is how the data will be stored in this table

Mention System - Posts Table Data

All the user’s post are stored in the  post_text  column of the posts table.

Here  @[4]  denotes the mention  – where 4 is the user id mentioned by the user 1

jQuery Plugin to Implement Mention Style Autocomplete Input

I have used jquery.mentionsInput plugin that allows you to “@mention” someone in a textarea box like facebook or twitter. This plugin is open source now.

It is nothing but a jQuery extension, so it naturally requires jQuery version (1.6+). In addition to jQuery, it also depends on  underscore.js  (1.2+), which is used to simplify the whole component. To make textarea box grow automatically while typing, you have to use  jquery.elastic.js 

HTML Form

Please add the class name  mention  to any textarea to get @mention feature

<form method="POST">
<textarea class="mention" cols="10" rows="3" placeholder="What's going on?" ></textarea>
<input type="button" value="Post" class="postMention">
</form>

Below jQuery code is used to get users suggestion from the database via ajax call while typing in the textarea. Response should be in JSON format. Ajax call will trigger after you type @ followed by characters


$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
 $.getJSON('ajax/get_users_json.php', function(responseData) {
 responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) &amp;gt; -1 });
 callback.call(this, responseData);
 });
}
});

 

 onDataRequest  – This function is a callback function which is used to provide data for the autocomplete from the database via ajax call

get_users_json.php – List all users in JSON format

$user_data = array();
$users = $DB->query("select * from users");

foreach($users as $key => $val)
{
$user_data[$key]['id'] = $val['user_id'];
$user_data[$key]['name'] = $val['user_name'];
$user_data[$key]['avatar'] = "https://cdn.w3lessons.info/logo.png";
$user_data[$key]['type'] = 'user';
}
header('Content-Type: application/json');
echo json_encode($user_data);

Output will be like this

[{
 "id": 1,
 "name": "w3lessons",
 "avatar": "https://cdn.w3lessons.info/logo.png",
 "type": "user"
 },
 {
 "id": 2,
 "name": "google",
 "avatar": "https://cdn.w3lessons.info/logo.png",
 "type": "user"
 }]

jQuery Code to Submit Form data

After clicking Post button, below javascript will be triggered and it gets the data from the textarea.

Below code will send the data to the php file called post.php via jQuery ajax call and process the mention text, store it into the database and return the response with mentioned username with hyperlink


$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
var post_data = "text="+encodeURIComponent(post_text);
$.ajax({
type: "POST",
data: post_data,
url: 'ajax/post.php',
success: function(msg) {
if(msg== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
}
});
} else {
alert("Post cannot be empty!");
}
});
});

Post.php – Process the mention text and store it into the Database

We are storing the data like @[1] in the database – Here 1 is the user_id of the mentioned user. In the frontend, I’m replacing the @[1] with @w3lessons by extracting the @mentions using PHP preg_match_all regrex function


if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
{
include 'config.php';
$user = 1; //w3lessons demo user

$text = strip_tags($_POST['text']); //clean the text

$DB->query("INSERT INTO posts(post_text,post_user_id) VALUES(?,?)", array($text,$user));
?>
<div class="media">
<div class="media-left">
<img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">w3lessons</h4>
<p><?php echo getMentions($text); ?></p>
</div>
</div>
<hr>
<?php
}

PHP Function to extract the @mentions in the content

 preg_match_all  regrex is used to search for any @ character in the given content and store them in  $matches  array.

Below function is used to parse the @mentions in the content and check the names with the database. If any text matches with username, then it will replace the names with the clickable urls


function getMentions($content)
{
global $DB;
$mention_regex = '/@\[([0-9]+)\]/i'; //mention regrex to get all @texts

if (preg_match_all($mention_regex, $content, $matches))
{
foreach ($matches[1] as $match)
{
$match_user =$DB->row("SELECT * FROM users WHERE user_id=?",array($match));

$match_search = '@[' . $match . ']';
$match_replace = '<a target="_blank" href="' . $match_user['user_profile_url'] . '">@' . $match_user['user_name'] . '</a>';

if (isset($match_user['user_id']))
{
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}

Many readers asked me to write about Facebook Style Mention Script with PHP and today I’m very glad that I wrote it for my fellow readers.

 

 

Related Posts