我在获取子类别时感到困惑,我想只回显每个子类别一次..

时间:2012-11-18 09:45:05

标签: php

请帮助我,在获取类别时我很困惑,我只想回应每个子类的一次..

<?php
mysql_connect("localhost", "root", "")or die(mysql_error())//connect to mysql;
mysql_select_db("ubcommerce")//select database;
$catagories = "";
$sql = mysql_query("SELECT * FROM inventory ORDER BY subcatagory DESC")//select data from table;
$found = mysql_num_rows($sql);
if ($found > 0) {
    while ($row = mysql_fetch_array($sql)) {
        // Gather all $row values into local variables for easier usage in output 
        $subcatagory = $row['subcatagory'];
        $link = $row['catagory'];
        $link = lcfirst($link);
        $catagories .= "<li>$subcatagory</li>";
    }
} else {
    $catagories = "you have no product in your list yet";
}
?>

<html>
    <body>

    <div class="col-content">
        <ul>
<?php echo $catagories; ?>
        </ul>
    </div>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

使用pdo;)

<?php
//connect to your db
$bdd = new PDO('mysql:host=localhost;dbname=test', 'root', 'ubcommerce');
//prepare your request
$bdd->prepare('SELECT * FROM inventory ORDER BY subcatagory DESC');
//exec your request
$bdd->execute();
//put your reponse into an array
$rep = $bdd->fetchAll();
//run your array
foreach($rep as $subCategory){
    echo $subCategory['catagory'];
}

答案 1 :(得分:0)

评论中详细解决问题的最简单方法是编写如下查询:

SELECT DISTINCT subcatagory FROM inventory ORDER BY subcatagory DESC

(虽然可能无法很好地扩展)