Skip to content

Instantly share code, notes, and snippets.

@code-boxx
Last active May 26, 2023 02:44
Show Gist options
  • Save code-boxx/5c2f7cd65e50968ccc5af08822c74c66 to your computer and use it in GitHub Desktop.
Save code-boxx/5c2f7cd65e50968ccc5af08822c74c66 to your computer and use it in GitHub Desktop.
PHP MYSQL Category Subcategory

PHP MYSQL CATEGORY & SUB-CATEGORY

https://code-boxx.com/categories-subcategories-php-mysql/

NOTES

  1. Create a database and import 1-category.sql.
  2. Change the database settings in 2-lib-category.php to your own.
  3. Access 3-draw.php in the browser – Study how the recursion works.
  4. Study 4-add-edit-del.php for the “admin functions”.

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) CATEGORY TABLE
CREATE TABLE `category` (
`category_id` bigint(20) NOT NULL,
`parent_id` bigint(20) NOT NULL DEFAULT 0,
`category_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `category`
ADD PRIMARY KEY (`category_id`),
ADD KEY `parent_id` (`parent_id`);
ALTER TABLE `category`
MODIFY `category_id` bigint(20) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;
-- (B) DUMMY DATA
INSERT INTO `category` (`category_id`, `parent_id`, `category_name`) VALUES
(1, 0, 'Electronics'),
(2, 1, 'Computers'),
(3, 1, 'Cameras'),
(4, 2, 'Desktop'),
(5, 2, 'Laptop');
<?php
class Category {
// (A) CONSTRUCTOR - CONNECT TO DATABASE
protected $pdo = null;
protected $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 CONNECTION
function __destruct() {
if ($this->stmt !== null) { $this->stmt = null; }
if ($this->pdo !== null) { $this->pdo = null; }
}
// (C) HELPER - RUN SQL QUERY
function query ($sql, $data=null) : void {
$this->stmt = $this->pdo->prepare($sql);
$this->stmt->execute($data);
}
// (D) GET ALL CATEGORIES RECURSIVELY
function getAll ($id=0) {
// (D1) GET CATEGORIES WITH GIVEN PARENT ID
$this->query("SELECT * FROM `category` WHERE `parent_id`=?", [$id]);
$cat = [];
while ($r = $this->stmt->fetch()) {
$cat[$r["category_id"]] = [
"n" => $r["category_name"],
"c" => null
];
}
// (D2) GET CHILDREN
if (count($cat)>0) {
foreach ($cat as $id => $c) { $cat[$id]["c"] = $this->getAll($id); }
return $cat;
} else { return null; }
}
// (E) GET ALL CHILDREN CATEGORY ID
function getChildren ($id) {
$this->query("SELECT `category_id` FROM `category` WHERE `parent_id`=?", [$id]);
$cat = $this->stmt->fetchAll(PDO::FETCH_COLUMN);
foreach ($cat as $cid) {
$cat = array_merge($cat, $this->getChildren($cid));
}
return $cat;
}
// (F) ADD NEW CATEGORY
function add ($name, $parent=0) {
$this->query(
"INSERT INTO `category` (`category_name`, `parent_id`) VALUES (?, ?)",
[$name, $parent]
);
return true;
}
// (G) UPDATE CATEGORY
function update ($name, $id, $parent) {
// (G1) CHECK PARENT ID
// PARENT ID CANNOT BE SET TO SELF + CANNOT MOVE UNDER CHILDREN
$cannot = $this->getChildren($id);
$cannot[] = $id;
if (in_array($parent, $cannot)) {
$this->error = "Invalid parent ID";
return false;
}
// (G2) UPDATE ENTRY
$this->query(
"UPDATE `category` SET `category_name`=?, `parent_id`=? WHERE `category_id`=?",
[$name, $parent, $id]
);
return true;
}
// (H) "SAFE DELETE" - CHILDREN WILL REVERT TO PARENT ID 0
function safeDel ($id) {
// (H1) GET ALL CHILDREN
$children = $this->getChildren($id);
// (H2) AUTO-COMMIT OFF
$this->pdo->beginTransaction();
// (H3) REVERT CHILDREN TO PARENT ID 0
if (count($children) > 0) {
$in = implode(",", $children);
$this->query("UPDATE `category` SET `parent_id`=0 WHERE `category_id` IN ($in)");
}
// (H4) DELETE CATEGORY
$this->query("DELETE FROM `category` WHERE `category_id`=?", [$id]);
// (H5) COMMIT;
$this->pdo->commit();
return true;
}
// (I) "CASCADE DELETE" - ALL CHILDREN WILL ALSO BE DELETED
function casDel ($id) {
// (H1) GET ALL CHILDREN + SET CURRENT ID
$in = $this->getChildren($id);
$in[] = $id;
$in = implode(",", $in);
// (H2) DELETE
$this->query("DELETE FROM `category` WHERE `category_id` IN ($in)");
return true;
}
}
// (J) 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", "");
// (K) NEW CATEGORY OBJECT
$_CAT = new Category();
<!DOCTYPE html>
<html>
<head>
<title>Nested Categories Demo</title>
<meta charset="utf-8">
</head>
<body>
<?php
// (A) GET ALL CATEGORIES
require "2-lib-category.php";
$all = $_CAT->getAll();
// (B) RECURSIVE DRAW CATEGORIES
function draw ($cat) {
echo "<ul>";
foreach ($cat as $id => $c) {
echo "<li>({$id}) {$c["n"]}";
if (is_array($c["c"])) { draw($c["c"]); }
echo "</li>";
}
echo "</ul>";
}
draw($all);
?>
</body>
</html>
<?php
// (A) LOAD LIBRARY
require "2-lib-category.php";
// (B) ADD NEW CATEGORY
// echo $_CAT->add("Smartphones", 2) ? "OK" : "ERROR" ;
// (C) UPDATE CATEGORY
// echo $_CAT->update("Computerzzz", 2, 3) ? "OK" : $_CAT->error ;
// (D) DELETE CATEGORY
// echo $_CAT->safeDel(2) ? "OK" : "ERROR" ;
// echo $_CAT->casDel(2) ? "OK" : "ERROR" ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment