Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /******** 120922 by cahyadsn@yahoo.com ********
- -- table category
- DROP TABLE IF EXISTS `category`;
- CREATE TABLE IF NOT EXISTS `category` (
- `id` int(11) UNSIGNED NOT NULL,
- `parent_id` int(11) UNSIGNED NOT NULL DEFAULT '0',
- `name` varchar(100) NOT NULL,
- PRIMARY KEY (`id`)
- ) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
- --
- -- example
- --
- INSERT INTO `category` (`id`, `parent_id`, `name`) VALUES
- (1,0,"node no 1"),
- (2,0,"node no 2"),
- (3,1,"node no 1.1"),
- (4,2,"node no 2.1"),
- (5,3,"node no 3.1.1"),
- (6,3,"node no 3.1.2");
- *************************************************/
- class category{
- var $mysqli;
- function __construct(){
- //--- database configuration
- $dbhost="localhost";
- $dbuser="root";
- $dbpass="";
- $dbname="test";
- //---- initiate database connection
- $this->mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
- if (mysqli_connect_error()) {
- die('Connect Error (' . mysqli_connect_errno() . ') '
- . mysqli_connect_error());
- }
- }
- function hasChild($parent_id)
- {
- $sql = "SELECT COUNT(*) as count FROM category WHERE parent_id = ' " . $parent_id . " ' ";
- $rs=$this->mysqli->query($sql)->fetch_object();
- return $rs->count;
- }
- function CategoryTree($list,$parent,$append)
- {
- $list = '<li>'.$parent->name.'</li>';
- if ($this->hasChild($parent->id)) // check if the id has a child
- {
- $append++; // this is our basis on what level is the category e.g. (child1,child2,child3)
- $list .= "<ul class='child child".$append." '>";
- $sql = "SELECT * FROM category WHERE parent_id = ' " . $parent->id . " ' ";
- $obj=$this->mysqli->query($sql);
- $child=$obj->fetch_object();
- do{
- $list .= $this->CategoryTree($list,$child,$append);
- }while($child = $obj->fetch_object());
- $list .= "</ul>";
- }
- return $list;
- }
- function CategoryList()
- {
- $list = "";
- $sql = "SELECT * FROM category WHERE (parent_id = 0 OR parent_id IS NULL)";
- $obj=$this->mysqli->query($sql);
- $parent=$obj->fetch_object();
- $mainlist = "<ul class='parent'>";
- do{
- $mainlist .= $this->CategoryTree($list,$parent,$append = 0);
- }while($parent = $obj->fetch_object());
- $list .= "</ul>";
- return $mainlist;
- }
- function __destruct()
- {
- $this->mysqli->close();
- }
- }
- //===================
- $category=new category();
- echo $category->CategoryList();
- ?>
Add Comment
Please, Sign In to add comment