Facebook Style Hashtag System with PHP, MYSQL & jQuery

Last modified on by Karthikeyan K

If you are not aware of Hashtag, then I will say you would not using any social networking sites in a very large extent.  Here I am going to explain you about the advantages of hashtag & how you can implement it in your web projects using php & mysql

What is Hashtag?

Hashtags are essentially a filter, allowing people to see the conversation associated with that word or phrase. Hashtags is alternative to tags..  Twitter is the first site to introduce the hashtag. But now a days sites like facebook, Instagram, Vine & Tumblr are using this feature in all platforms. If you use the hashtag effectively then you will get the contents across different sites together in a single page.

Facebook like Hashtag System with PHP

Database Design

To create Facebook Like Hashtag System ,  You need to create one table called “Messages”

CREATE TABLE IF NOT EXISTS `messages` (
`id` int(12) NOT NULL AUTO_INCREMENT,
`message` text COLLATE utf8_unicode_ci NOT NULL,
`hashtag` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
`time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

Data will be stored like this

Facebook Style Hashtag Table Design

Php Code to Filter Hashtag from Text

function gethashtags($text)
{
//Match the hashtags
preg_match_all('/(^|[^a-z0-9_])#([a-z0-9_]+)/i', $text, $matchedHashtags);
$hashtag = '';
// For each hashtag, strip all characters but alpha numeric
if(!empty($matchedHashtags[0])) {
foreach($matchedHashtags[0] as $match) {
$hashtag .= preg_replace("/[^a-z0-9]+/i", "", $match).',';
}
}
//to remove last comma in a string
return rtrim($hashtag, ',');
}
//usage
$text = "w3lessons.info - #php programming blog, #facebook wall script";
echo gethashtags($text); //output - php,facebook

We need to convert hashtags into clickable links. Here is the simple php function that will convert #hashtag, @mentions & normal http, https links into clickable links

function convert_clickable_links($message)
{
$parsedMessage = preg_replace(array('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))/', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i'), array('<a href="$1" target="_blank">$1</a>', '$1<a href="">@$2</a>', '$1<a href="index.php?hashtag=$2">#$2</a>'), $message);
return $parsedMessage;
}

Update.php

Here config.php contains the information about database settings and functions.php contains gethashtags & convert_clickable_links functions

if(isset($_POST['msg']) && $_POST['msg'] != '')
{
require_once 'config.php';
require_once 'functions.php';
$message = strip_tags(trim($_POST['msg']));
//get hashtag from message
$hashtag = gethashtags($message);

//insert into messages table
$query = mysql_query("INSERT INTO `messages` (`message`, `hashtag`) VALUES ('$message', '$hashtag')") or die(mysql_error());
$ins_id = mysql_insert_id();
?>
<div class="msg_body" id="<?php echo $ins_id;?>">
<div class="msg_img">
<img src="http://0.gravatar.com/avatar/82620dd66b22b34a915303b93b92929b" />
</div>
<div class="msg_text">
<?php echo convert_links($message); ?>
<div class="time">5 seconds ago</div>
</div>
</div>
<?php
mysql_close();
}

index.php

If the hashtag parameter is present in the url, then I will filter the messages for corresponding hashtag. If not then I will list all the messages

 if(isset($_GET['hashtag']) && $_GET['hashtag'] != '') {
$tags = trim($_GET['hashtag']);
$result = mysql_query("SELECT * FROM `messages` WHERE hashtag LIKE '%$tags%' ORDER BY `id` DESC");
$title = "Search results for <font color='red'>".$tags."</font> <a href='index.php'>clear</a>";
} else {
$result = mysql_query("SELECT * FROM `messages` ORDER BY `id` DESC");
$title = "Updates";
}
?>
<h3><?php echo $title; ?></h3>
<div id="updates">
<?php
$total_rows = mysql_num_rows($result);
if($total_rows > 0) {
while($row = mysql_fetch_array($result)) {?>
<div class="msg_body" id="message<?php echo $row['id'];?>">
<div class="msg_img"> <img src="https://0.gravatar.com/avatar/82620dd66b22b34a915303b93b92929b" /> </div>
<div class="msg_text"> <?php echo convert_links($row['message']);?>
<div class="time"><?php echo $row['time'];?></div>
</div>
</div>
<?php } }
</div>

jQuery Code

function updatedata() {
//preloader
$('#post-loader').show();
var msg = $("#message").val();
if(msg != '') {
$.ajax({
type: "POST",
url: "update.php",
data: 'msg='+msg,
cache: false,
success: function(html) {
$('#updates').prepend(html);
$('#post-loader').hide();
$("#message").val('');
},
error: function() {
$('#post-loader').hide();
}
});
return false;
} else {
alert("Message cannot be empty!");
return false;
}
}

Status Update Form

  <div class="msg-container">
<div class="msg-form-content">
<div class="msg-form-header"> Update Status
<div class="msg-loader" id="post-loader" style="display:none"><img src="loading.gif" /></div>
</div>
<form id="form" name="form" action="" method="POST" >
<div class="msg-form-inner">
<textarea id="message" class="message-form" placeholder="What's on your mind?" name="message"></textarea>
</div>
<div type="button" name="action" class="msg-btn" value="Post"><a onclick="updatedata()" class="uibutton large confirm">Post</a></div>
</form>
</div>
</div>

Please don’t forget to share and subscribe to latest updates of the blog.

Thanks!

View Live Demo & Download

You May Also Like

21 Responses

  1. Web design company says:

    can’t download after I subscribe , it’s said Email does not exist in our database. Please use below form to subscribe

  2. etenzy says:

    sorry, but the database has a large fault…
    you will need 3 tables, if you want to follow the normal forms…

    1. `messages`
    2. `hashtags`
    3. `message_hashtags`

    CREATE TABLE IF NOT EXISTS `messages` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `message` text COLLATE utf8_unicode_ci NOT NULL,
    `time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

    CREATE TABLE IF NOT EXISTS `hashtags` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `hashtag` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

    CREATE TABLE IF NOT EXISTS `message_hashtags` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `messageId` int(11) NOT NULL,
    `hashtagId` int(11) NOT NULL,
    PRIMARY KEY (`id`),
    INDEX (`messageId`),
    CONSTRAINT
    FOREIGN KEY (`messageId`)
    REFERENCES `messages` (`id`)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
    INDEX (`hashtagId`),
    CONSTRAINT
    FOREIGN KEY (`hashtagId`)
    REFERENCES `hashtags` (`id`)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;

  3. sailesh says:

    can’t download after I subscribe , it’s said Email does not exist in our database. Please use below form to subscribe

  4. syed says:

    Cannot download

  5. utsavgupta says:

    Cannot Download even after Subscribing…Can you please update the subscribers database

  6. Lucas FERRARI says:

    Wow, an incredible easy to use PHP code, thanks 🙂
    It will help me to create my little social network 😉

  7. Ali says:

    hi please update email database .

    i can’t download .

  8. MICKIE says:

    Function is “convert_clickable_links” but U R using convert_links in index.php & update.php
    LINE 18 :

  9. Bobi Ohrid says:

    I need to get this script more faster than 10 hours. Can you please send it to my mail:
    avramoski123@gmail.com
    Thanks

  10. bac vu says:

    please support update my email vubactest1@gmail.com. I just submit subscribed. Thank you so much.

  11. BButter says:

    I can’t download it. I have been subscribe for 2 days ago.

  12. India India says:

    I can’t download it.
    Please accept my subscription, i am still waiting.

  13. Awadhesh Kumar says:

    livemail.awadhesh@gmail.com unable to download, plz update ur db

  14. Bob Mars says:

    mysqli? its ridiculous stop using mysql its PDO OR MYSQLI GET TO 2017 WE ARE NO LONGER IN 2015

Leave a Reply

Your email address will not be published. Required fields are marked *