Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active December 15, 2023 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code-boxx/d47ba7185781d7127a461c76cff5288b to your computer and use it in GitHub Desktop.
Save code-boxx/d47ba7185781d7127a461c76cff5288b to your computer and use it in GitHub Desktop.
PHP MYSQL Hashtag System

PHP MYSQL HASHTAG SYSTEM

https://code-boxx.com/hashtag-system-php-mysql/

NOTES

  1. Create a test database and import 1-database.sql.
  2. Change the database settings in 2-lib-tag.php to your own.
  3. Access 4a-tag.html in the browser - Enter a few test messages with hashtags, then do a search by hashtag.

LICENSE

Copyright by Code Boxx

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

-- (A) POSTS
CREATE TABLE `posts` (
`post_id` bigint(20) NOT NULL,
`post_txt` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `posts`
ADD PRIMARY KEY (`post_id`),
ADD FULLTEXT KEY `post_txt` (`post_txt`);
ALTER TABLE `posts`
MODIFY `post_id` bigint(20) NOT NULL AUTO_INCREMENT;
-- (B) TAGS
CREATE TABLE `tags` (
`post_id` bigint(20) NOT NULL,
`tag` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `tags`
ADD PRIMARY KEY (`post_id`,`tag`);
<?php
class Tag {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = "";
function __construct () {
$this->pdo = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET,
DB_USER, DB_PASSWORD, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
}
// (B) DESTRUCTOR - CLOSE DATABASE CONNECTION
function __destruct () {
if ($this->stmt!==null) { $this->stmt = null; }
if ($this->pdo!==null) { $this->pdo = null; }
}
// (C) HELPER FUNCTION - EXECUTE SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) SAVE POST + TAGS
function save ($txt, $tags=null, $id=null) {
// (D1) ADD/UPDATE POST
if ($id==null) {
$this->query("INSERT INTO `posts` (`post_txt`) VALUES (?)", [$txt]);
} else {
$this->query("UPDATE `posts` SET `post_txt`=? WHERE `post_id`=?", [$txt, $id]);
}
// (D2) DELETE OLD TAGS
if ($id==null) { $id = $this->pdo->lastInsertId(); }
else { $this->query("DELETE FROM `tags` WHERE `post_id`=?", [$id]); }
// (D3) INSERT NEW TAGS
if ($tags != null) {
$tags = json_decode($tags, true);
$sql = "INSERT INTO `tags` (`post_id`, `tag`) VALUES ";
$data = [];
foreach ($tags as $t) {
$sql .= "(?,?),";
$data[] = $id; $data[] = $t;
}
$this->query(substr($sql, 0, -1).";", $data);
}
// (D4) DONE
return true;
}
// (E) GET POSTS
function get ($tag=null) {
// (E1) GET ALL
if ($tag==null) { $this->query("SELECT * FROM `posts`"); }
// (E2) SEARCH BY TAG
else {
$sql = "SELECT p.* FROM `tags` `t`
JOIN `posts` `p` USING (`post_id`)
WHERE `tag`=?";
$this->query($sql, [$tag]);
}
// (E3) FETCH!
return $this->stmt->fetchAll();
}
}
// (F) DATABASE SETTINGS - CHANGE TO YOUR OWN!
define("DB_HOST", "localhost");
define("DB_NAME", "test");
define("DB_CHARSET", "utf8mb4");
define("DB_USER", "root");
define("DB_PASSWORD", "");
// (G) NEW HASH TAG OBJECT
$_TAG = new Tag();
<?php
if (isset($_POST["req"])) {
require "2-lib-tag.php";
switch ($_POST["req"]) {
// (A) GET POSTS
case "get":
echo json_encode($_TAG->get(
isset($_POST["tag"]) ? $_POST["tag"] : null
));
break;
// (B) SAVE POST
case "save":
echo $_TAG->save(
$_POST["txt"],
isset($_POST["tags"]) ? $_POST["tags"] : null,
isset($_POST["id"]) ? $_POST["id"] : null
) ? "OK" : $_TAG->error;
break;
}}
<!DOCTYPE html>
<html>
<head>
<title>PHP MySQL Hashtag</title>
<meta charset="utf-8">
<script src="4b-tag.js"></script>
<link rel="stylesheet" href="4c-tag.css">
</head>
<body>
<!-- (A) ADD POST -->
<form onsubmit="return htag.save()">
<input type="text" required id="add"
placeholder="Post some dummy messages with #hashtags">
<input type="submit" value="Post">
</form>
<!-- (B) SEARCH BY TAG -->
<form onsubmit="return htag.get(true)">
<input type="text" id="search"
placeholder="Then search by hashtag">
<input type="submit" value="Search">
</form>
<!-- (C) POSTS -->
<div id="posts"></div>
</body>
</html>
var htag = {
// (A) INITIALIZE
hAdd : null, // html add post field
hSearch : null, // html search field
hPosts : null, // html posts <div>
init : () => {
// (A1) GET HTML ELEMENTS
htag.hAdd = document.getElementById("add");
htag.hSearch = document.getElementById("search");
htag.hPosts = document.getElementById("posts");
// (A2) LOAD POSTS
htag.get();
},
// (B) GET/SEARCH POSTS
get : search => {
// (B1) FORM DATA
let data = new FormData();
data.append("req", "get");
if (search == true) {
data.append("tag", htag.hSearch.value);
}
// (B2) FETCH & DRAW HTML
fetch("3-ajax-tag.php", { method : "post", body : data })
.then(res => res.json())
.then(data => {
htag.hPosts.innerHTML = "";
data.forEach(post => {
let row = document.createElement("div");
row.className = "row";
row.innerHTML = post["post_txt"];
htag.hPosts.append(row);
});
});
return false;
},
// (C) SAVE POST
save : () => {
// (C1) GET TAGS
let matches = htag.hAdd.value.match(/(^|\s)(#[a-z\d-]+)/g),
tags = matches === null ? null : [...new Set(matches)];
if (tags!=null) {
tags.forEach((t, i) => { tags[i] = t.substring(2); });
}
// (C2) FORM DATA
let data = new FormData();
data.append("req", "save");
data.append("txt", htag.hAdd.value);
if (tags!=null) { data.append("tags", JSON.stringify(tags)); }
// (C3) POST + UPDATE HTML LIST
fetch("3-ajax-tag.php", { method : "post", body : data })
.then(res => res.text())
.then(txt => {
if (txt == "OK") {
htag.hAdd.value = "";
htag.get();
} else { alert(txt); }
});
// (C4) DONE
return false;
}
};
window.onload = htag.init;
/* (A) WHOLE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
body {
max-width: 500px;
margin: 0 auto;
background: #f5f5f5;
}
/* (B) ADD & SEARCH FORMS */
form {
display: flex;
padding: 15px;
background: #505050;
}
input[type=text], input[type=submit] { padding: 10px; }
input[type=text], input[type=submit] { border: 0; }
input[type=text] { flex-grow: 1; }
input[type=submit] {
width: 80px;
font-weight: 700;
color: #fff;
background: #b73b3b;
cursor: pointer;
}
/* (C) POSTS LIST */
#posts {
padding: 15px;
background: #ebebeb;
}
#posts .row {
padding: 15px;
background: #fff;
border: 1px solid #ddd;
margin: 15px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment