Jump to content

[SOLVED] Categories and Sub-cat


php2MySQL

Recommended Posts

hiiiiiii,

 

i have a big big big problem,i'm trying to solve it since 5 days  :-\ , i have a table(cats)

=============

id int(3) PK

name varchar(100)

parent int(3)

=============

And i want to display the data from this table like this:

 

 

261bf6e6198365303ffd57849046ccf9eff96245.jpg

 

please note that the code must be unlimited sub-categories

i need to discussion this issue with you .

 

Thanks.

Link to comment
Share on other sites

 

This is my Table:

 

CREATE TABLE `cats` (
  `id` int(9) NOT NULL auto_increment,
  `name` varchar(255) default NULL,
  `parent` int(9) default NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=10 DEFAULT CHARSET=cp1256;

INSERT INTO `cats` VALUES ('1', 'Cat1', '-1');
INSERT INTO `cats` VALUES ('2', 'Cat2', '-1');
INSERT INTO `cats` VALUES ('3', 'Cat3', '-1');
INSERT INTO `cats` VALUES ('4', 'sub1', '1');
INSERT INTO `cats` VALUES ('5', 'sub2', '2');
INSERT INTO `cats` VALUES ('6', 'sub3', '3');
INSERT INTO `cats` VALUES ('7', 'subsub1', '4');
INSERT INTO `cats` VALUES ('8', 'subsubsub1', '7');


 

<?php
include("inc/config.php");
$DB=new db;
function listSubcats ($parent, $level=0) {
global $DB;
         $res = $DB->exe("SELECT id, name FROM cats
                              WHERE parent = '$parent'
                              ORDER BY name");
         while (list($id, $name) = $DB->fetch_row($res)) {
                $indent = str_repeat('>', $level);
                echo "<OPTION value='$id'>$indent $name</OPTION>\n";
                listSubcats($id, $level+1);
         }
}
// End Function tst
echo "<SELECT name='cat'>";
$res=$DB->exe("select * from cats");
while($bb=$DB->fetch_array($res))
{
listSubcats($bb['parent']);
}
echo '</SELECT>';
?>

 

When i run the code its showen as image below:

 

51d83a261573475c7aa82a2880be222ae152e253.jpg

 

Please note that when the parent is -1 its mean that has no parent.

 

 

Thanks,

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.