Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 05: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/6fb28ddfcf920b81843d2ab9ddba6d70 to your computer and use it in GitHub Desktop.
Save code-boxx/6fb28ddfcf920b81843d2ab9ddba6d70 to your computer and use it in GitHub Desktop.
PHP MYSQL Notice Board

PHP MYSQL NOTICE BOARD

https://code-boxx.com/simple-notice-board-php-mysql/

IMAGES

cork

NOTES

  1. Create a test database and import 1-database.sql.
  2. Edit 2-lib-notes.php, change the database settings to your own.
  3. Launch 3a-notice-board.html in the browser. Captain Obvious, use http:// and not file://.

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.

CREATE TABLE `notes` (
`note_id` bigint(20) NOT NULL,
`note_sort` bigint(20) NOT NULL DEFAULT 0,
`note_txt` text CHARACTER SET utf8mb4 NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `notes`
ADD PRIMARY KEY (`note_id`);
ALTER TABLE `notes`
MODIFY `note_id` bigint(20) NOT NULL AUTO_INCREMENT;
<?php
class Notes {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
private $pdo = null;
private $stmt = null;
public $error = null;
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 - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET ALL NOTES
function getAll () {
$this->query("SELECT * FROM `notes` ORDER BY `note_sort` ASC");
return $this->stmt->fetchAll();
}
// (E) SAVE NOTE
function save ($txt, $id=null) {
// (E1) ADD NEW
if ($id==null) {
$this->query("UPDATE `notes` SET `note_sort`=`note_sort`+1");
$this->query("INSERT INTO `notes` (`note_sort`, `note_txt`) VALUES (?,?)", [0, $txt]);
}
// (E2) UPDATE
else {
$this->query("UPDATE `notes` SET `note_txt`=? WHERE `note_id`=?", [$txt, $id]);
}
// (E3) DONE
return true;
}
// (F) DELETE NOTE
function del ($id) {
$this->query("DELETE FROM `notes` WHERE `note_id`=?", [$id]);
return true;
}
// (G) SAVE SORT ORDER
function order ($order) {
foreach (json_decode($order) as $sort=>$nid) {
$this->query("UPDATE `notes` SET `note_sort`=? WHERE `note_id`=?", [$sort, $nid]);
}
return true;
}
}
// (H) 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", "");
// (I) NEW NOTES OBJECT
$_NOTE = new Notes();
<!DOCTYPE html>
<html>
<head>
<title>Notice Board Demo</title>
<meta charset="utf-8">
<script src="3b-notice-board.js"></script>
<link rel="stylesheet" href="3c-notice-board.css">
</head>
<body>
<!-- (A) ADD/UPDATE NOTE -->
<form id="noteform">
<input type="text" id="notetxt" required disabled>
<input type="submit" id="notego" value="Add" disabled>
</form>
<!-- (B) NOTICE BOARD -->
<div id="board"></div>
<!-- (C) SIMPLE INSTRUCTIONS
Enter text and "add" to create a new note.
Drag-and-drop a note to rearrange.
Double click on a note to edit.
Hover over a note and click on "X" to delete it.
-->
</body>
</html>
var board = {
// (A) HELPER - AJAX FETCH
fetch : (data, load) => {
// (A1) FORM DATA
let form = new FormData();
for (let [k,v] of Object.entries(data)) { form.append(k,v); }
// (A2) FETCH
fetch("4-ajax.php", { method:"POST", body:form })
.then(res => res.text())
.then(txt => load(txt))
.catch(err => console.error(err));
},
// (B) INITIALIZE NOTICE BOARD
notes : [], // current list of notes
hwrap : null, // html notice board wrapper
hform : null, // html add/update note form
hadd : null, // html add/update note text field
hgo : null, // html add/update note button
hid : "", // note id currently being edited
hsel : null, // current note being dragged or edited
init : () => {
// (B1) GET HTML ELEMENTS
board.hwrap = document.getElementById("board");
board.hform = document.getElementById("noteform");
board.hadd = document.getElementById("notetxt");
board.hgo = document.getElementById("notego");
// (B2) ENABLE ADD NEW NOTE
board.hform.onsubmit = () => board.save();
board.hadd.disabled = false;
board.hgo.disabled = false;
// (B3) LOAD & DRAW HTML NOTES
board.show();
},
// (C) SHOW NOTES
show : () => { board.fetch(
{"req" : "show"},
txt => {
// (C1) SET NEW HTML + GET ALL NOTES
board.hwrap.innerHTML = txt;
board.notes = document.querySelectorAll("#board .note");
// (C2) ATTACH "EDIT", "DELETE", "SORT"
if (board.notes.length>0) { for (let div of board.notes) {
// (C2-1) DOUBLE CLICK TO EDIT
div.ondblclick = () => board.edit(div);
// (C2-2) CLICK TO DELETE
div.querySelector(".del").onclick = () => board.del(div);
// (C2-3) ON DRAG START - ADD DROPPABLE HINTS
div.ondragstart = e => {
board.hsel = e.target;
for (let n of board.notes) {
n.classList.add("drag");
if (n != board.hsel) { n.classList.add("hint"); }
}
};
// (C2-4) ON DRAG ENTER - HIGHLIGHT DROPZONE
div.ondragenter = e => {
if (div != board.hsel) { div.classList.add("active"); }
};
// (C2-5) DRAG LEAVE - REMOVE HIGHLIGHT DROPZONE
div.ondragleave = e => div.classList.remove("active");
// (C2-6) DRAG END - REMOVE ALL HIGHLIGHTS
div.ondragend = e => { for (let n of board.notes) {
n.classList.remove("drag");
n.classList.remove("hint");
n.classList.remove("active");
}};
// (C2-7) DRAG OVER - PREVENT DEFAULT "DROP", SO WE CAN DO OUR OWN
div.ondragover = e => e.preventDefault();
// (C2-8) ON DROP - REORDER NOTES & SAVE
div.ondrop = e => {
// (C2-8-1) PREVENT DEFAULT BROWSER DROP ACTION
e.preventDefault();
if (e.target != board.hsel) {
// (C2-8-2) GET CURRENT & DROPPED POSITIONS
let idrag = 0, // index of currently dragged
idrop = 0; // index of dropped location
for (let i=0; i<board.notes.length; i++) {
if (board.hsel == board.notes[i]) { idrag = i; }
if (e.target == board.notes[i]) { idrop = i; }
}
// (C2-8-3) REORDER HTML NOTES
if (idrag > idrop) {
board.hwrap.insertBefore(board.hsel, e.target);
} else {
board.hwrap.insertBefore(board.hsel, e.target.nextSibling);
}
// (C2-8-4) GET NEW ORDER
board.notes = board.hwrap.querySelectorAll(".note");
let order = [];
for (let n of board.notes) { order.push(n.dataset.id); }
// (C2-8-5) AJAX SAVE ORDER
board.fetch({
"req" : "order",
"order" : JSON.stringify(order)
}, txt => {
if (txt == "OK") { board.show(); }
else { alert(txt); }
});
}
};
}}
}
); },
// (D) EDIT NOTE
edit : note => {
// (D1) SELECTED NOTE & NOTE ID
board.hsel = note.querySelector(".txt");
board.hid = note.dataset.id;
// (D-2) LOCK - NO DRAG NO DELETE WHILE EDITING
for (let n of board.notes) { n.classList.add("lock"); }
// (D-3) UPDATE NOTE FORM
board.hadd.value = board.hsel.innerHTML;
board.hgo.value = "Update";
// board.hadd.focus();
board.hadd.select();
},
// (E) SAVE NOTE
save : () => {
// (E1) AJAX POST
board.fetch({
"req" : "save",
"note_id" : board.hid,
"note_txt" : board.hadd.value
},
// (E2) ON SERVER RESPONSE
txt => {
// (E2-1) EDIT MODE ONLY - RESTORE NOTE FORM & ENABLE NOTES
if (board.hid != "") {
board.hid = "";
board.hgo.value = "Add";
board.hsel = board.hadd.value;
for (let n of board.notes) { n.classList.remove("lock"); }
}
// (E2-2) PASS/FAIL
if (txt == "OK") {
board.hadd.value = "";
board.show();
} else { alert(txt); }
});
return false;
},
// (F) DELETE NOTE
del : note => { if (confirm("Delete note?")) {
board.fetch({
"req" : "del",
"note_id" : note.dataset.id
}, txt => {
if (txt == "OK") { board.show(); }
else { alert(txt); }
});
}}
};
window.addEventListener("DOMContentLoaded", board.init);
/* (A) ENTIRE PAGE */
* {
font-family: arial, sans-serif;
box-sizing: border-box;
}
body {
padding: 20px;
margin: 0;
background: url(cork.jpg);
}
/* (B) ADD NEW NOTE */
#noteform {
display: flex;
margin-bottom: 20px;
}
#notetxt { flex-grow: 1; }
#notetxt, #notego { border: 0; }
#notetxt { padding: 10px; }
#notego {
padding: 10px 20px;
font-size: 18px;
color: #fff;
background: #0e5ce9;
}
/* (C) NOTICE BOARD WRAPPER */
#board {
display: grid;
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px;
}
/* (D) NOTES */
div.note {
position: relative;
padding: 15px;
border: 2px solid #fdff8a;
background: #fdff8a;
box-shadow: 9px 11px 11px -2px rgba(0,0,0,0.4);
}
/* (E) DELETE BUTTON */
div.note .del {
position: absolute;
top: 5px; right: 5px;
color: #ff5a5a;
font-size: 20px;
font-weight: 700;
display: none;
}
div.note:hover .del { display: block; }
/* (F) EDIT NOTE */
div.note .txt input {
padding: 5px;
border: 0;
background: #fff;
}
div.note .txt input:focus { outline-width: 0; }
/* (G) LOCK DRAG & DELETE WHEN EDITING */
#board div.lock {
pointer-events: none;
color: #818181;
border: 1px solid #d3d3d3;
background: #d3d3d3;
}
#board div.lock .del { display: none; }
/* (H) PREVENT DRAG LEAVE EVENT ON NOTE CHILD ELEMENTS */
#board div.drag .txt, #board div.drag .del { pointer-events: none; }
#board div.drag .del { display: none; }
/* (I) DRAG HIGHLIGHT */
#board div.hint {
border: 2px dashed #ff8e68;
background: #feffc5;
}
#board div.active {
border: 2px dashed #ff0000;
background: #fcff00;
}
<?php
if (isset($_POST["req"])) {
require "2-lib-notes.php";
switch ($_POST["req"]) {
// (A) INVALID REQUEST
default: echo "Invalid request"; break;
// (B) SHOW ALL NOTES
case "show":
$notes = $_NOTE->getAll();
if (count($notes)>0) { foreach ($notes as $n) {
printf(
"<div class='note' draggable='true' data-id='%u'>
<div class='del'>X</div>
<div class='txt'>%s</div>
</div>",
$n["note_id"], $n["note_txt"]
);
}}
break;
// (C) SAVE NOTE
case "save":
echo $_NOTE->save($_POST["note_txt"], $_POST["note_id"])
? "OK" : "ERROR";
break;
// (D) DELETE NOTE
case "del":
echo $_NOTE->del($_POST["note_id"])
? "OK" : "ERROR";
break;
// (E) SAVE NEW ORDER
case "order":
echo $_NOTE->order($_POST["order"])
? "OK" : "ERROR";
break;
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment