0

table : categories

    -------------------------------------------
    | id | cat_name_en   | parent_id          |
    -------------------------------------------
    | 1  | level 1       |          0         |
    | 2  | level 2       |          1         |
    | 3  | Level 3       |          2         |
    | 4  | Level 4       |          3         |
    | 5  | level 5       |          4         |
    | 6  | test          |          1         |

here i need to get the name as

level 5 > level 4 > level 3 > level 2 > level 1

in my query i got names only upto 2

SELECT category,cat_id FROM ( SELECT CONCAT(p.cat_name_en, ' > ', c.cat_name_en) AS 'category',c.id as cat_id FROM categories c LEFT JOIN categories p ON c.parent_id = p.id ) s where cat_id = 5
executable
  • 3,365
  • 6
  • 24
  • 52
Rp9
  • 1,955
  • 2
  • 23
  • 31

2 Answers2

0
function CategoryTree(&$output=null, $parent=0, $indent=null){
    // conection to the database
    $db = new PDO("mysql:host=localhost;dbname=tutorial", 'root', '');
    // select the categories that have on the parent column the value from $parent
    $r = $db->prepare("SELECT id, name FROM categories WHERE parent=:parentid");
    $r->execute(array(
        'parentid'  => $parent
    ));
    // show the categories one by one
    while($c = $r->fetch(PDO::FETCH_ASSOC)){
        $output .= '<option value=' . $c['id'] . '>' . $indent . $c['name'] . "</option>";
        if($c['id'] != $parent){
            // in case the current category's id is different that $parent
            // we call our function again with new parameters
            CategoryTree($output, $c['id'], $indent . "&nbsp;&nbsp;");
        }
    }
    // return the list of categories
    return $output;
}
Yaroslaw
  • 98
  • 4
0

Since you have maximum 5 levels of category, you can add LEFT JOIN for each level to form a hierarchy as needed,

SELECT t1.id as cat_id,
CONCAT_WS(' > ', t1.cat_name_en, t2.cat_name_en, t3.cat_name_en, t4.cat_name_en, t5.cat_name_en)
FROM categories AS t1
LEFT JOIN categories AS t2 ON t2.id = t1.parent_id
LEFT JOIN categories AS t3 ON t3.id = t2.parent_id 
LEFT JOIN categories AS t4 ON t4.id = t3.parent_id
LEFT JOIN categories AS t5 ON t5.id = t4.parent_id
WHERE t1.id = 5;

CONCAT_WS will not concat NULL values.

Samir Selia
  • 7,007
  • 2
  • 11
  • 30
  • @Rp9 what this answer does not really directly explain.. You need to add or remove LEFT JOIN's to match the sub sub levels needed.. – Raymond Nijland Nov 14 '18 at 10:21