如何使用stmt语句结果对mysqli标题菜单类别和子类别进行分组并按父级显示

问题描述 投票:0回答:1

如何对类别和子类别进行分组并显示标题菜单的 Misqli DB 的所有结果?我制作了一个名为

category
的表,其中包含 3 列
id, category, parent
,然后使用
parent
对类别进行分组,其中值
parent=0
代表类别,子类别值与主类别对应的父类别。但问题是代码只显示了第一个主类别和第一个相应的子类别,而我想显示全部。

所以我有3个类别值(

fruits id=1 , parent=0
cars id=2 parent=0
clothes id=3 parent=0
parent=0
表示它们是类别标题),例如对于汽车,我有 2 个子类别值 (
moto id=52 parent=2
auto id=34 parent=2
) 你明白了...

$parentTake = '0';
$categorieDrowdown = "";
$categorieDrowdownLista = "";
$stmt = $con->prepare('SELECT id, category, parent FROM category WHERE parent=?');
    $stmt->bind_param('i', $parentTake);
    $stmt->execute();
    $existCount = $stmt->store_result();
        if($existCount == 0){
    echo "nU ai nici o categorie adaugata";
     exit();
        }
    $stmt->bind_result($idParent, $categorie, $parent);
    while ($stmt->fetch())    {
        $idParent;
        $categorie;
        $categorieDrowdown .= '<li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> '.$categorie.'<span class="caret"></span></a>       
            ';      
                    
    $stmt = $con->prepare('SELECT id, category, parent FROM category WHERE parent=?');
    $stmt->bind_param('i', $idParent);
    $stmt->execute();
    $existCount = $stmt->store_result();
        if($existCount == 0){
    echo "nU ai nici o subcategorie lista adaugata";
     exit();
        }
    $stmt->bind_result($idLista, $categorieLista, $parentLista);
    while ($stmt->fetch())    {
        $idLista;
        $categorieLista;
        $categorieDrowdownLista .= ' <ul class="dropdown-menu">
        <li><a href="#">'.$categorieLista.'</a></li>
            </ul>
        </li>      
            ';
        }//close while subcategorie
    }//close while  categorie first select

和显示屏

   <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
      <ul class="nav navbar-nav">
        <li class="active"><a href="#">Home </a></li>
        <li><a href="#">Admin CMS</a></li>
        <?php echo $categorieDrowdown;//CATEGORIE PRIMA ex: fructe?>    
        <?php echo $categorieDrowdownLista;//CATEGORIE SECUNDA ex:mere?>    
               
      </ul>

抱歉我的英语和我的问题,但我是新手

php loops mysqli while-loop
1个回答
0
投票

您正在用第二个

$stmt
变量覆盖第一个
$stmt
,这就是为什么您只获得第一个菜单项及其子类别。我对您的代码进行了一些调整,并添加了一种替代方法,该方法不会像循环查询那样对性能造成影响。另外值得一提的是,如果您没有子类别,则不应退出脚本。只需创建一个空占位符,以便您可以继续页面加载。

$stmt->store_result();
不返回行数。您调用它可以访问
$stmt->num_rows
属性,这将为您提供找到的行的结果。请注意,我没有在第二个示例中存储结果( mysqli::store_result() ),我只是填充
$menu
数组,甚至不需要知道是否有结果。

$start = microtime( true );
$output = '';

$stmt = $con->prepare( '
    SELECT
        id, category, parent
    FROM category
    WHERE parent = 0
' );
$stmt->execute();
$stmt->store_result();
// YOU DON'T WANT TO DO THIS... o.O it's fine for debuging tho
//~ if($stmt->num_rows == 0){
    //~ echo "nU ai nici o categorie adaugata";
    //~ exit();
//~ }
// INSTEAD
if( $stmt->num_rows > 0 ){
$stmt->bind_result($idParent, $categorie, $parent);
    while ($stmt->fetch()){
        $output .= '
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                ' . $categorie . ' <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">';

        // rename $stmt to $stmt2 so you'll not overwrite the initial statement
        $stmt2 = $con->prepare('SELECT id, category, parent FROM category WHERE parent=?');
        $stmt2->bind_param('i', $idParent);
        $stmt2->execute();
        $stmt2->store_result();
        // NOR THIS... o.O
        //~ if($stmt2->num_rows == 0){
            //~ echo "nU ai nici o subcategorie lista adaugata";
            //~ exit();
        //~ }
        // INSTEAD
        if( $stmt2->num_rows > 0 ){
            $stmt2->bind_result($idLista, $categorieLista, $parentLista);
            while ($stmt2->fetch()){
                $output .= '
                <li>
                    <a href="#">'.$categorieLista.'</a>
                </li>';
            } //close while subcategorie
        }
        $output .= '
            </ul>
        </li>';
    } // close while  categorie first select
}

echo $output, "\n\n\n";
echo 'Duration: ', microtime( true ) - $start, "\n\n\n";

//-----------------------------------------------------------

// I LIKE IT THIS WAY... ONLY FOR 1 SUBLEVEL THO
// for unlimited dept sub categories you need different approce
$start = microtime( true );
unset( $output );
$output = '';
$menu = array();
$sel = $con->prepare( '
    SELECT
        id, category, parent
    FROM category
    ORDER BY parent, category ASC
' );
$sel->execute();
$sel->bind_result( $id, $category, $parent );
while( $sel->fetch() ){
    if( ! $parent ){ // same as $parent == 0
        $menu[ $id ] = array(
            'name' => $category,
            'sub'  => array(),
        );
    } else {
        $menu[ $parent ]['sub'][ $id ] = array(
            'name' => $category,
        );
    }
}
$sel->close();
foreach( $menu as $id => $item ){
    $output .= '
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
            ' . $item['name'] . ' <span class="caret"></span>
        </a>
        <ul class="dropdown-menu">';
    foreach( $item['sub'] as $subid => $subitem ){
        $output .= '
            <li>
                <a href="#">' . $subitem['name'] . '</a>
            </li>';
    }
    $output .= '
        </ul>
    </li>';
}
//~ echo '<pre>', var_dump( $menu ), '</pre>';
echo $output, "\n\n\n";
echo 'Duration: ', microtime( true ) - $start, "\n\n\n";

输出示例:

        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                fruits <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
                <li>
                    <a href="#">apple</a>
                </li>
                <li>
                    <a href="#">orange</a>
                </li>
                <li>
                    <a href="#">banana</a>
                </li>
                <li>
                    <a href="#">Pen Pineapple Apple Pen</a>
                </li>
            </ul>
        </li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                cars <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
                <li>
                    <a href="#">moto</a>
                </li>
                <li>
                    <a href="#">auto</a>
                </li>
            </ul>
        </li>
        <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
                clothes <span class="caret"></span>
            </a>
            <ul class="dropdown-menu">
                <li>
                    <a href="#">skirt</a>
                </li>
            </ul>
        </li>


Duration: 0.0020129680633545



    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
            cars <span class="caret"></span>
        </a>
        <ul class="dropdown-menu">
            <li>
                <a href="#">auto</a>
            </li>
            <li>
                <a href="#">moto</a>
            </li>
        </ul>
    </li>
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
            clothes <span class="caret"></span>
        </a>
        <ul class="dropdown-menu">
            <li>
                <a href="#">skirt</a>
            </li>
        </ul>
    </li>
    <li class="dropdown">
        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
            fruits <span class="caret"></span>
        </a>
        <ul class="dropdown-menu">
            <li>
                <a href="#">apple</a>
            </li>
            <li>
                <a href="#">banana</a>
            </li>
            <li>
                <a href="#">orange</a>
            </li>
            <li>
                <a href="#">Pen Pineapple Apple Pen</a>
            </li>
        </ul>
    </li>


Duration: 0.00058293342590332

数据库结构和数据

CREATE TABLE `category` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `category` varchar(255) NOT NULL,
  `parent` int(10) NOT NULL DEFAULT '0',
  PRIMARY KEY (`id`),
  KEY `parent` (`parent`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8;

INSERT INTO `category` (`id`, `category`, `parent`) VALUES
(1, 'fruits', 0),
(2, 'cars', 0),
(3, 'clothes', 0),
(4, 'moto', 2),
(5, 'auto', 2),
(6, 'apple', 1),
(7, 'orange', 1),
(8, 'banana', 1),
(9, 'skirt', 3),
(10, 'Pen Pineapple Apple Pen', 1);
© www.soinside.com 2019 - 2024. All rights reserved.