Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active December 11, 2023 02:47
Show Gist options
  • Save code-boxx/7be8b545ca35cb3b441a49be90755796 to your computer and use it in GitHub Desktop.
Save code-boxx/7be8b545ca35cb3b441a49be90755796 to your computer and use it in GitHub Desktop.
PHP MYSQL Simple Messaging System

PHP MYSQL MESSAGING SYSTEM

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

IMAGES

x-girl

NOTES

  1. Create a database, import 1-database.sql.
  2. Change the database settings in 2-lib-msg.php to your own.
  3. Launch 4-demo-msg.php in the browser and test send some messages.
  4. Change $_SESSION["user"] in 2-lib-msg.php to act as another user.

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) USERS
CREATE TABLE `users` (
`user_id` bigint(20) NOT NULL,
`user_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `users`
ADD PRIMARY KEY (`user_id`);
ALTER TABLE `users`
MODIFY `user_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
INSERT INTO `users` (`user_id`, `user_name`) VALUES
(1, 'Joe Doe'),
(2, 'Jon Doe'),
(3, 'Joy Doe');
-- (B) MESSAGES
CREATE TABLE `messages` (
`user_from` bigint(20) NOT NULL,
`user_to` bigint(20) NOT NULL,
`date_send` datetime NOT NULL DEFAULT current_timestamp(),
`date_read` datetime DEFAULT NULL,
`message` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `messages`
ADD PRIMARY KEY (`user_from`, `user_to`, `date_send`),
ADD KEY `date_read` (`date_read`);
<?php
class Message {
// (A) CONSTRUCTOR - CONNECT TO THE 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) EXECUTE SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET ALL USERS & NUMBER OF UNREAD MESSAGES
function getUsers ($for) {
// (D1) GET USERS
$this->query("SELECT * FROM `users` WHERE `user_id`!=?", [$for]);
$users = [];
while ($r = $this->stmt->fetch()) { $users[$r["user_id"]] = $r; }
// (D2) COUNT UNREAD MESSAGES
$this->query(
"SELECT `user_from`, COUNT(*) `ur`
FROM `messages` WHERE `user_to`=? AND `date_read` IS NULL
GROUP BY `user_from`", [$for]);
while ($r = $this->stmt->fetch()) { $users[$r["user_from"]]["unread"] = $r["ur"]; }
// (D3) RESULTS
return $users;
}
// (E) GET MESSAGES
function getMsg ($from, $to, $limit=30) {
// (E1) MARK ALL AS "READ"
$this->query(
"UPDATE `messages` SET `date_read`=NOW()
WHERE `user_from`=? AND `user_to`=? AND `date_read` IS NULL", [$from, $to]);
// (E2) GET MESSAGES
$this->query(
"SELECT m.*, u.`user_name` FROM `messages` m
JOIN `users` u ON (m.`user_from`=u.`user_id`)
WHERE `user_from` IN (?,?) AND `user_to` IN (?,?)
ORDER BY `date_send` DESC
LIMIT 0, $limit", [$from, $to, $from, $to]);
return $this->stmt->fetchAll();
}
// (F) SEND MESSAGE
function send ($from, $to, $msg) {
$this->query(
"INSERT INTO `messages` (`user_from`, `user_to`, `message`) VALUES (?,?,?)",
[$from, $to, strip_tags($msg)]
);
return true;
}
}
// (G) 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", "");
// (H) MESSAGE OBJECT
$_MSG = new Message();
// (I) ACT AS USER
session_start();
// $_SESSION["user"] = ["id" => 1, "name" => "Joe Doe"];
// $_SESSION["user"] = ["id" => 2, "name" => "Jon Doe"];
$_SESSION["user"] = ["id" => 3, "name" => "Joy Doe"];
<?php
if (isset($_POST["req"])) {
require "2-lib-msg.php";
switch ($_POST["req"]) {
// (A) SHOW MESSAGES
case "show":
$msg = $_MSG->getMsg($_POST["uid"], $_SESSION["user"]["id"]);
if (count($msg)>0) { foreach ($msg as $m) {
$out = $m["user_from"] == $_SESSION["user"]["id"]; ?>
<div class="mRow <?=$out?"mOut":"mIn"?>">
<div class="mDate"><?=$m["date_send"]?></div>
</div>
<div class="mRow <?=$out?"mOut":"mIn"?>"><div class="mRowMsg">
<div class="mSender"><?=$m["user_name"]?></div>
<div class="mTxt"><?=$m["message"]?></div>
</div></div>
<?php }}
break;
// (B) SEND MESSAGE
case "send":
echo $_MSG->send($_SESSION["user"]["id"], $_POST["to"], $_POST["msg"])
? "OK" : $_MSG->error ;
break;
}}
<!DOCTYPE html>
<html>
<head>
<title>Users List</title>
<meta charset="utf-8">
<link rel="stylesheet" href="x-demo-msg.css">
<script src="5-demo-msg.js"></script>
</head>
<body>
<?php
// (A) GET USERS
require "2-lib-msg.php";
$users = $_MSG->getUsers($_SESSION["user"]["id"]); ?>
<!-- (B) LEFT : USER LIST -->
<div id="uLeft">
<!-- (B1) CURRENT USER -->
<div id="uNow">
<div><img src="x-girl.png"></div>
<div><?=$_SESSION["user"]["name"]?></div>
</div>
<!-- (B2) USER LIST -->
<?php foreach ($users as $uid=>$u) { ?>
<div class="uRow" id="usr<?=$uid?>" onclick="msg.show(<?=$uid?>)">
<div class="uName"><?=$u["user_name"]?></div>
<div class="uUnread"><?=isset($u["unread"])?$u["unread"]:0?></div>
</div>
<?php } ?>
</div>
<!-- (C) RIGHT : MESSAGES LIST -->
<div id="uRight">
<!-- (C1) SEND MESSAGE -->
<form id="uSend" onsubmit="return msg.send()">
<input type="text" id="mTxt" required>
<input type="submit" value="Send">
</form>
<!-- (C2) MESSAGES -->
<div id="uMsg"></div>
</div>
</body>
</html>
var msg = {
// (A) HELPER - AJAX FETCH
ajax : (data, after) => {
// (A1) FORM DATA
let form = new FormData();
for (const [k,v] of Object.entries(data)) { form.append(k, v); }
// (A2) FETCH
fetch("3-ajax-msg.php", { method:"POST", body:form })
.then(res => res.text())
.then(txt => after(txt))
.catch(err => console.error(err));
},
// (B) SHOW MESSAGES
uid : null, // current selected user
show : uid => {
// (B1) SET SELECTED USER ID
msg.uid = uid;
// (B2) GET HTML ELEMENTS
let hForm = document.getElementById("uSend"),
hTxt = document.getElementById("mTxt"),
hUnread = document.querySelector(`#usr${uid} .uUnread`),
hMsg = document.getElementById("uMsg");
// (B3) SET SELECTED USER
for (let r of document.querySelectorAll(".uRow")) {
if (r.id=="usr"+uid) { r.classList.add("now"); }
else { r.classList.remove("now"); }
}
// (B4) SHOW MESSAGE FORM
hForm.style.display = "flex";
hTxt.value = "";
hTxt.focus();
// (B5) AJAX LOAD MESSAGES
hMsg.innerHTML = "";
msg.ajax({
req : "show",
uid : uid
}, txt => {
hMsg.innerHTML = txt;
hUnread.innerHTML = 0;
});
},
// (C) SEND MESSAGE
send : () => {
let hTxt = document.getElementById("mTxt");
msg.ajax({
req : "send",
to : msg.uid,
msg : hTxt.value
}, txt => {
if (txt == "OK") {
msg.show(msg.uid);
hTxt.value = "";
} else { alert(txt); }
});
return false;
}
};
/* (A) ENTIRE PAGE */
* {
font-family: Arial, Helvetica, sans-serif;
box-sizing: border-box;
}
/* (B) LAYOUT */
body {
padding: 0; margin: 0;
width: 100vw; height: 100vh;
display: flex;
align-items: stretch;
}
#uLeft, #uRight { overflow: auto; }
#uLeft {
width: 170px;
color: #fff;
background: #3a3a3a;
}
#uRight {
flex-grow: 1;
background: #fafafa;
}
/* (C) LEFT : USERS LIST */
/* (C1) SHARED */
#uNow, .uRow { padding: 10px; }
/* (C2) CURRENT USER */
#uNow {
font-weight: 700;
background: #1e1e1e;
text-align: center;
}
#uNow img {
width: 80px;
border-radius: 50%;
margin-bottom: 5px;
}
/* (C3) USERS LIST */
.uRow {
display: flex;
align-items: center;
border-bottom: 1px solid #545454;
}
.uRow:hover {
cursor: pointer;
background: #2e2e2e;
}
.uRow.now {
background: #890e0e;
font-weight: 700;
}
.uName { flex-grow: 1; }
.uUnread {
text-decoration: none;
display: inline-block;
color: #fff;
background: #1e1e1e;
padding: 5px;
margin-right: 5px;
}
/* (D) RIGHT : MESSAGES */
/* (D1) SEND MESSAGE FORM */
#uSend {
display: none;
padding: 15px;
background: #eee;
}
#uSend input { padding: 10px; }
#uSend input[type=text] {
flex-grow: 1;
border: 0;
}
#uSend input[type=submit] {
color: #fff;
background: #890e0e;
border: 0;
}
/* (D2) MESSAGES - SHARED */
.mRow {
display: flex;
margin: 10px;
}
.mOut { flex-direction: row; }
.mIn { flex-direction: row-reverse; }
.mRowMsg {
position: relative;
padding: 10px;
border-radius: 10px;
}
.mDate { color: #a7a7a7; }
.mSender, .mDate { font-size: 0.8em; }
.mTxt {
padding: 5px 0;
font-size: 1.1em;
}
/* (D3) MESSAGES - SENT */
.mOut .mRowMsg {
margin-left: 20px;
background: #dde5ff;
}
.mOut .mTxt { color: #212491; }
.mOut .mSender { color: #9295fd; }
/* (D3) MESSAGES - RECEIVED */
.mIn .mRowMsg {
margin-right: 20px;
text-align: right;
background: #ffe7e7;
}
.mIn .mTxt { color: #c52020; }
.mIn .mSender { color: #dfa9a9; }
/* (D4) SPEECH BUBBLE TAIL */
.mRowMsg::after {
position: absolute;
content: "";
border: 13px solid transparent;
}
.mOut .mRowMsg::after {
border-right-color:#dde5ff;
border-left: 0;
margin-top: -13px;
top: 50%;
left: -13px;
}
.mIn .mRowMsg::after {
border-left-color:#ffe7e7;
border-right: 0;
margin-top: -13px;
top: 50%;
right: -13px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment