在MySQL数据库中显示PHP中的类别和子类别

时间:2016-11-22 01:17:54

标签: php html mysql

我试图在网站上显示一个类别和子目录列表,这些列表是从MySQL数据库中填充的,而且我对如何正确执行它有点生疏。

基本上我想实现这个目标:

Parent Cat 1 
--Child Cat1
--Child Cat2
Parent Cat 2
Parent Cat 3
--Child Cat 1
--Child Cat 2

并且数据库已经布局:

ParentCat1,   ChildCat1,   Item1
ParentCat1,   ChildCat1,   Item2
ParentCat1,   ChildCat2,   Item1
ParentCat2,                Item1
ParentCat3,   ChildCat1,   Item1
ParentCat3,   ChildCat2,   Item2

EDIT 到目前为止,这要归功于Gowtham:

<?php
    $conn = mysql_connect("localhost", "USER", "PASS");

    if (!$conn) {
        echo "Unable to connect to DB: " . mysql_error();
        exit;
    }

    if (!mysql_select_db("DB-Store")) {
        echo "Unable to select DB-Store: " . mysql_error();
        exit;
    }

    $sql = "SELECT * FROM menu";

    $result = mysql_query($sql);

    if (!$result) {
        echo "Could not successfully run query ($sql) from DB: " . mysql_error();
        exit;
    }

    if (mysql_num_rows($result) == 0) {
        echo "No rows found, nothing to print";
        exit;
    }

    $result = mysql_query($sql);
    $menu = array();
    echo "Start of Array";
    echo "<br>";
    while ($row = mysql_fetch_assoc($result)) {
        $menu['category'][] = $result['cat'];
        if (!empty($result['subcat']))
        $menu['subcat'][$result['cat']][] = $result['subcat'];          
    }

    foreach ($menu['category'] as $cat) {
        echo $cat."<br>";
        foreach ($menu['subcat'][$cat] as $subcat) {
            echo "--" . $subcat."<br>";
        }
    }
    echo "<br>";
    echo "End of Array";
    mysql_free_result($result);
?>

1 个答案:

答案 0 :(得分:0)

我要做的第一件事就是从数据库获取值并将其存储在数组中并运行循环来打印数组。

这是我的代码。让我们考虑类别字段名称是cat,子类别字段名称是subcat,表名是菜单,那么

<?php

$sql = 'select * from menu';
$con = mysqli_connect("localhost", "my_user", "my_password", "my_db");
// Check connection
if (mysqli_connect_errno()) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

// Perform queries
$result = mysqli_query($con, $sql);

$menu = array();
while ($row = mysqli_fetch_assoc($result)) {
    if (!in_array($row['cat'], $menu['category'])) {

            $menu['category'][] = $row['cat'];
    }
    if (!empty($row['subcat']))
        $menu['subcat'][$row['cat']][] = $row['subcat'];
}

foreach ($menu['category'] as $cat) {
    echo $cat."<br>";
    foreach ($menu['subcat'][$cat] as $subcat) {
        echo "--" . $subcat."<br>";
    }
}
?>

上述程序将满足您的需求。