NHANWEB

Xây dựng Hashtag sử dụng PHP, MySQL & jQuery

Hashtag giờ là một phần quan trọng trên các trang web mạng xã hội như FaceBook và các mạng xã hội hàng đầu khác.Tôi còn nhớ, hashtag lần đầu tiên được sử dụng bởi Twitter đã tạo ra một làn sóng ủng hộ mạnh mẽ rồi lan sang các mạng xã hội khác như một trào lưu mới. Lần lượt các mạng xã hội khác như tumblr, facebook, instagram… cũng bắt đầu đưa hashtag vào sử dụng trong hệ mạng của mình. Nó giúp cho người dùng tìm kiếm một chủ đề theo một từ khóa một cách dễ dàng và sử dụng nó khá đơn giản: chỉ cần #hashtag là xong.

Một status sử dụng Hashtag trên FaceBook

Hôm nay, tôi sẽ cùng bạn thử xây dựng một hệ thống hashtag như vậy trên website mình.

Tạo database

Trước tiên, để đưa hashtag vào sử dụng, bạn cần một kiến trúc để lưu trữ các hashtag trong database. Chúng ta tạo một database đơn giản như sau:

[code] CREATE TABLE IF NOT EXISTS `message` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`message` text NOT NULL,
`hashtag` varchar(255) NOT NULL,
PRIMARY KEY (`id`)
)
[/code]

Với database này, dữ liệu được lưu trữ như sau:

Dữ liệu lưu trữ trong table mới tạo

Filter dữ liệu nhập

Trong phần này, chúng ta sẽ viết một hàm (function) cho phép bạn kiểm tra dữ liệu nhập vào để so sánh trong dữ liệu có sử dụng #hashtag hay không. Chúng ta sử dụng hàm preg_match_all() để tìm kiếm trong chuỗi nhập như sau:

[code language=”php”] <!–?php
//function to filter the hashtag
function hashtag($msg){
//filter the hastag
preg_match_all(‘/(^|[^a-z0-9_])#([a-z0-9_]+)/i’, $msg, $matched_hashtag);
$hashtag = ”;
//if hashtag found
if(!empty($matched_hashtag[0])){
//fetch hastag from the array
foreach ($matched_hashtag[0] as $matched) {
//append every hastag to a string
//remove the # by preg_replace function
$hashtag .= preg_replace(‘/[^a-z0-9]+/’, ”, $matched).’,’;
//append and , after every hashtag
}
}
//remove , from the last hashtag
return rtrim($hashtag, ‘,’);
}
?–>
[/code]

Hàm chuyển http:// và #hashtag vào link

Chúng ta có hàm như sau:

[code language=”php”] <!–?php
//function to convert the url & hashtag into link
function convert_to_links($msg){
$final_message = preg_replace(array(‘/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<–>]+|\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\))+(?:\(([^\s()&lt;&gt;]+|(\([^\s()&lt;&gt;]+\)))*\)|[^\s`!()\[\]{};:\’".,&lt;&gt;?«»“”‘’]))/’, ‘/(^|[^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>’), $msg);
return $final_message;
}
?&gt;
[/code]

HTML

Hai hàm chính đã xong, giờ chúng ta tiến hành xây dựng form HTML để nhập liệu. Tôi xây dựng một form với ID là postForm bao gồm một textarea, một nút submit và một thẻ span với ID là loader cho phép hiển thị hình ảnh đang tải trang khi tôi click chuột vào nút submit.

[code] <h2>Facebook Styled Hashtag</h2>
<form action="" method="post" id="postForm">
<textarea id="message" placeholder="Whats on your Mind?"></textarea>
<input type="submit" value="post">
<span id="feedback" style="display:none;"><img src="loader.gif" style="height:25px;float:right;"></span>
</form>
[/code]

jQuery (javascript)

Tôi sử dụng jQuery để gửi dữ liệu được điền từ form postForm và đưa dữ liệu này vào file update.php để xử lý sau đó cho hiện ra ở một thẻ có ID là post_contaiiner. Code của chúng ta như sau:

[code] <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(‘#postForm’).submit(function(){
var feedback = $(‘#feedback’);
var message = $(‘#message’);
//check that the message is empty or not
if(message.val() != ”){
feedback.show();
$.post(‘update.php’, {msg:message.val()}, function(response){
$(‘#post_container’).prepend(response);
feedback.hide();
message.val(”);
});
}else{
alert(‘Please enter a message’);
}
return false;
});
});
</script>
[/code]

Kết nối với cơ sở dữ liệu

Phần này tôi đã có một bài viết trước đây và khá đầy đủ rồi. Tôi chỉ đăng code và không giải thích thêm nhiều nha:

[code language=”php”] <!–?php
//connect to the database
define(‘host’, ‘localhost’);
define(‘username’, ‘root’);
define(‘password’, ”);
define(‘db’, ‘hunklessons’);
$connect = mysql_connect(host,username,password) or die(mysql_error(‘Could not Connect To database’));
$database = mysql_select_db(db) or die(mysql_error(‘Database not found’));
?–>
[/code]

Phần code này để thuận tiện sử dụng tôi đặt vào file connect.php để sử dụng.

Update.php

Giờ chúng ta bắt đầu viết file update.php để cập nhật dữ liệu gửi từ form thông qua jQuery như tôi đã nói đến ở trên. Trong file này tôi cũng tiến hành cập nhật nội dung vào cơ sở dữ liệu (database) để truy vấn ở lần sau.

Nội dung như sau:

[code language=”php”] <!–?php
require ‘connect.php’;
require ‘function.php’;
if(isset($_POST[‘msg’]) && !empty($_POST[‘msg’])){
$msg = mysql_real_escape_string(strip_tags(trim($_POST[‘msg’])));
//get the hastag
$hashtags = hashtag($msg);
//insert into db
$query = mysql_query("INSERT INTO `message` (`message`,`hashtag`) VALUES (‘$msg’, ‘$hashtags’)");
$final_msg = convert_to_links($msg);
echo ‘<div id="posts"–>
<ul>
<li><img src="image.jpg"></li>
<li>’.$final_msg.'</li>
<ul>
‘;
}
?&gt;
[/code]

Xuất dữ liệu tìm kiếm

Trang này chúng ta sử dụng để xuất ra các dữ liệu có liên quan đến #hashtag của chúng ta. Tương tự như việc bạn tìm kiếm dựa trên hashtag trên FaceBook, Twitter… vậy.

[code language=”php”] <!–?php
//if hashtag is requested
if(isset($_GET[‘hashtag’]) && !empty($_GET[‘hashtag’])){
$hashtag = mysql_real_escape_string(strip_tags(trim($_GET[‘hashtag’])));
$query = mysql_query("SELECT * FROM message WHERE hashtag LIKE ‘%$hashtag%’ ORDER BY id DESC");
$title = "Search Result For <span style=’color:red;’–>".$hashtag." <a href="index.php">clear</a>";
}else{ // if not
$query = mysql_query("SELECT * FROM message ORDER BY id DESC LIMIT 15");
$title = "All Updates";
}
?&gt;
<div id="post_container">
<!–?php
echo $title;
//display the messages
if(mysql_num_rows($query) –> 0){
while ($row = mysql_fetch_assoc($query)) {
$final_msg = convert_to_links($row[‘message’]);
echo ‘<div id="posts">
<ul>
<li><a target="_blank" href="http://hunklessons.blogspot.in/"><img src="image.jpg"></a></li>
<li>’.$final_msg.'</li>
<ul>
</ul></ul></div>’;
}
}
?&gt;
<!–post will go here–>
</div>
[/code]

Xong :)

Exit mobile version