How do I arrange <ul> & <li> for recursive PHP function? I made as follows, but does not work properly :
<?php
echo '<ul>';
$sql = mysql_query("select * from categories where parent_id = 0");
while($rs=mysql_fetch_array($sql)){
echo '<li>'.$rs['name'];
echo show_subcategory(($rs['cat_id']));
echo '</li>';
}
echo '</ul>';
function show_subcategory($category_id){
$sql = mysql_query("select * from categories where parent_id ='$category_id'");
if(mysql_num_rows()>0){
echo '<ul>';
while($rs=mysql_fetch_array($sql)){
echo '<li>'.$rs['name'];
echo show_subcategory(($rs['cat_id']));
echo '</ul></li>';
}
}else{
echo '</li>';
}
}
?>
CREATE TABLE IF NOT EXISTS categories (
cat_id int(11) NOT NULL AUTO_INCREMENT,
parent_id int(11) NOT NULL DEFAULT '0',
name varchar(20) NOT NULL,
description text NOT NULL,
slug varchar(50) NOT NULL,
PRIMARY KEY (cat_id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=8 ;
INSERT INTO categories (cat_id, parent_id, name, description, slug) VALUES
(1, 0, 'programming', 'Forum ', 'programming'),
(2, 1, 'php', 'php programming', 'php'),
(3, 1, 'python', '', ''),
(4, 1, 'java', '', ''),
(5, 1, 'visual basic', '', ''),
(6, 2, 'codeigniter', '', ''),
(7, 2, 'joomla', '', '');
Since it’s a recursive function that’s supposed to output each category and a list of all sub-categories, you could move the “top-level” parent-category display into it as well (and start it by calling
show_subcategory(0);.After that, we can remove the sub-closing
</ul>and</li>tags and it would give us something similar to:Side-note, not answer specific:
I would recommend upgrading to the MySQLi or PDO extensions. Both support prepared statements which offer security against SQL-Injection attacks (which your current code is vulnerable to).