无限分类

来源:互联网 发布:用ubuntu破解wifi 编辑:程序博客网 时间:2024/04/28 03:08
<?php
header("Content-Type:text/html;charset=utf-8");
class category
{
    function __construct(){
    }
    
    public function getDB(){
        $dbms='mysql';
        $dbName='test';
        $user='root';
        $pass='';
        $host='localhost';
        $dsn="$dbms:host=$host;dbname=$dbName";
        try{
            $pdo=new PDO($dsn,$user,$pass);
            $names ='set names utf8';
            $result = $pdo->prepare($names);
            $result->execute();    
            return $pdo;
        }catch(Exception $e){
            echo $e->getMessage();
        }
    }
    
    public function query(){
        $query = 'select * from category order by categoryParentID';
        $pdo = $this->getDB();
        $result = $pdo->prepare($query);
        $result->execute();
        $list = $result->fetchALL(PDO::FETCH_ASSOC);
        return $list;
    }
    
    
    public function getChildren($id,$flag){
        $sql = "SELECT * FROM category a JOIN category b
                 on b.categoryParentID=a.categoryID
                where a.categoryID=$id";
        $pdo = $this->getDB();
        $result = $pdo->prepare($sql);
        $result->execute();
        $list = $result->fetchALL(PDO::FETCH_ASSOC);
        //print_r($list);exit;
        $num = count($list);
        $flag.=$flag;
        foreach($list as $v){
            echo $flag.$v['categoryID'].'<br>';
                $this->getChildren($v['categoryID'],$flag);
        }

    }

}

$object = new category();
$object->getChildren(1,'--');
?>


DROP TABLE IF EXISTS `category`;
CREATE TABLE `category` (
  `categoryID` smallint(5) unsigned NOT NULL AUTO_INCREMENT,
  `categoryParentID` smallint(5) unsigned NOT NULL DEFAULT '0',
  `categoryName` varchar(50) NOT NULL DEFAULT '',
  PRIMARY KEY (`categoryID`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;


INSERT INTO `category` VALUES ('1', '0', '一级类别');
INSERT INTO `category` VALUES ('2', '1', '二级类别');
INSERT INTO `category` VALUES ('3', '1', '二级类别');
INSERT INTO `category` VALUES ('4', '1', '二级类别');
INSERT INTO `category` VALUES ('5', '2', '三级类别');
INSERT INTO `category` VALUES ('6', '2', '三级类别');
INSERT INTO `category` VALUES ('7', '2', '三级类别');
INSERT INTO `category` VALUES ('8', '3', '三级类别');
INSERT INTO `category` VALUES ('9', '4', '三级类别');
INSERT INTO `category` VALUES ('10', '5', '四级类别');

0 0
原创粉丝点击