For a small blog with a limited count of categories, I wrote this code to fetch categories and subcategories from the database.
I used a recursive function to call all categories and sub categories , my goal since I do not have a lot of results is to get them all and display them.
So here is my code. I wish to get your feedback about it.
<?php
//mysql cat table table
/*
CREATE TABLE `cat` (
`id` int(255) NOT NULL,
`id_parent` int(255) DEFAULT NULL,
`name` varchar(255) NOT NULL,
`descr` varchar(1000) NOT NULL
)
*/
//preparing dsn var for PDO
$dsn = 'mysql:host=localhost;dbname=dbname';
//instantiating pdo object
$pdo = new PDO($dsn, "dbuser", 'dbpass');
//make a function take sql and pdo object
function getCats($sql, $pdo) {
//preparing sql statment
$stmt = $pdo->prepare($sql);
//executing our query
$stmt->execute();
//saving results in array
$array = $stmt->fetchAll();
//checking if array siez is zero we return 1;
if ($array == []) {
return 1;
}
//var_dump($array);
//outputting html list for all our cats
echo "<ul>";
for ($i = 0; $i < count($array); $i++) {
echo "<li>";
echo $array[$i]['name'];
echo "</li>";
//calling recursive function to get sub cats
getCats("SELECT * from cat where id_parent = {$array[$i][0]}", $pdo);
}
echo '</ul>';
}
//calling the function
getCats("SELECT * from cat where id_parent is NULL", $pdo);