Simple Hashtag System with PHP, MYSQL & jQuery

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.

Please check my popular article on Facebook / Twitter Style Mention System with PHP, MYSQL & jQuery

Contents

What is Hashtag & Why do we use 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.

Checkout my latest article on How to find @mention in a string  using PHP regrex

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

Below php code is used to filter the hashtag (#text) from any paragraphs in your web applications. You need to call the function called <ins>gethashtags($text)</ins> with parameter as texts.

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;
}

PHP Code to update hashtags into Mysql Table – 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;
}
}

Facebook Like 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>
I believe this tutorial helps you in providing the information, you have searched for in this website. I am open to accept any projects for other requirement or any customization on this PHP hashtag Module. I am good at all amazon web services, feel free to contact me at karthi@w3lessons.info for any help.

If you find this tutorial useful, please share it with your friends and in social networks.

Your suggestions/comments are most welcome

 

You May Also Like

Never Miss Any Web Tutorials, Guides, Tips and Free eBooks

Join Our Community Of 50,000+ Web Lovers and get a weekly newsletter in your inbox

 

I hate spam too. Unsubscribe at any time.

23 thoughts on “Simple Hashtag System with PHP, MYSQL & jQuery”

  1. i checked your facebook-style-hashtag-system and php-mention-system both are working good for hashtag system. but my concern is if i want both functionality in one code how can i integrate.

    facebook-style-hashtag-system : it showing #tag and linking for hashtag and we can add new hashtags. but it doesn’t have autofill selection

    php-mention-system: it have autofill selection from database but don’t have create new hashtags. here we can use only tags from database. if user wants to enter new hashtag it won’t allowing

    please help me to sort or integrate these two options.

    Reply
  2. I registered as new users subscribe but now 24h later I getting this: Email does not exist in our database.
    I would like to download the script ????

    Reply
  3. 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 ;

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

    Reply

Leave a Comment