Aibol Orazbekov Aibol Orazbekov - 6 months ago 16
MySQL Question

Display categories and subcategories in php mysql

Cant get categories and subcategories in php mysql.

Here i get all categories (cats and subcats):

function get_categories() {
$conn = db_connect();
$query = "select * from categories";
$result = $conn->query($query);
if(!$result) {
return false;
}else {
$result = db_result_to_array($result);
return $result;
}
}


And here i get subcats:

function get_child_cats($parent_id) {
$conn = db_connect();

$query = "select * from categories where parent_id = '".$parent_id."'";

$result = $conn->query($query);

if(!$result) {
return false;
}else {
$result = db_result_to_array($result);
return $result;
}

}


The
db_result_to_array()
function is here:

function db_result_to_array($result) {
$res_array = array();
for($count = 0; $row = $result->fetch_assoc(); $count++) {
$res_array[$count] = $row;
}
return $res_array;
}


DB consists of
cat_id, cat_name, parent_id


Here i am trying to display cats and subcats:

if(is_array($categories)) {
echo "<ul>";
foreach($categories as $row) {

if(!$row['parent_id']) {
$childs = get_child_cats($parent_id);
echo "<li>".$row['cat_name'];
if($row['parent_id']) {
echo "<ul>";
foreach($childs as $row) {
echo "<li>".$row['cat_name']."</li>";
}
echo "</ul>";
}
echo "</li>";
}

}
echo "</ul>";
}


However, i am getting only cats without any subcats.

Answer

You have written wrong logic, think your first condition is if(!$row['parent_id']) { and afterwards inside it you add condition if($row['parent_id']) {. so if "false" condition satisfy and cursor goes inside "if" then how it would be possible to execute logic for "true" for the same parameter and condition

I have tried below to make your logic correct:

foreach($categories as $row) {
    if(!$row['parent_id']) {
        echo "<li>".$row['cat_name'];
        $childs = get_child_cats($parent_id);

    }
    else {
        echo "<ul>";
        foreach($childs as $row) {
            echo "<li>".$row['cat_name']."</li>";
         }
       echo "</ul>";
    }
    echo "</li>";
}

Hope it works for you!