用php分类mySQL表

时间:2014-02-04 13:10:53

标签: php mysql

我有一个名为business的mySQL表,有4列。


名称,网址,说明,类别


我正在尝试将整个目录显示在每个相应类别名称下的页面上。有没有比我到目前为止更好的方法呢?我想将所有数据保存在一个表中,而不是为每个类别提供一个表。

<?php

$con = mysql_connect('localhost','username','password')
    or die('Could not connect: ' . mysql_error());
mysql_select_db('relicc_dogedir')
    or die('Could not select database');

$result = mysql_query("SELECT * FROM businesses ORDER BY category",$con);

$column = array();
    while($row = mysql_fetch_array($result))
    {
            $column[] = $row['category'];
    }
    $merged_column = array_unique($column);
    $refined_categories = array_values($merged_column);

    foreach ($refined_categories as &$refined_category)
    { ?>
        <h3><?php echo $refined_category;?></h3><?php 

        //Display sorted business names with corresponding category


    }

mysql_close($con);
?>

2 个答案:

答案 0 :(得分:0)

您可以在PHP中按category对数据进行分组。

...
$result = mysql_query("SELECT * FROM businesses ORDER BY category, name", $con);

$data = array();
while($row = mysql_fetch_array($result))
{
    $data[$row['category']][] = $row;
}

foreach($data as $categoryName => $categoryData) {
    echo '<h3>' . $categoryName . '</h3>';
    foreach ($categoryData as $business) {
        // display sorted business data using business
        // echo $business['name'];
    }
}
...

答案 1 :(得分:0)

首先,您应该知道不推荐使用mysql扩展,您应该使用MySQLiPDO_MySQL

您可以先检索类别,然后foreach类别检索相应的商家。

    try
    {
        $dbh = new PDO('mysql:host=localhost;dbname=YOURDB', 'USERNAME', 'PASSWORD');
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
        die;
    }

    $stmt = $dbh->query('SELECT category FROM businesses GROUP BY category');
    $stmt->setFetchMode(PDO::FETCH_ASSOC);

    $categories = $stmt->fetchAll();
    foreach ($categories as $category)
    {
        echo '<h3>'.$category['category'].'</h3>';

        $stmt = $dbh->prepare('SELECT * FROM businesses WHERE category = :categoryName');
        $stmt->bindParam(':categoryName', $category['category'], PDO::PARAM_STR);
        $stmt->execute();
        $businesses = $stmt->fetchAll();

        foreach ($businesses as $business)
        {
            echo $business['name'];
            echo '<br />';
        }
    }