0

I have a SQL table with two fields: City and State. I would like to build a simple list of all states and all respective cities, but until now could not. I would like something like this:

<ul>
<li>New York
    <ul>
    <li>Albany</li>
    <li>Buffalo</li>
    <li>New York City</li>
    </ul>
</li>
<li>Illinois
    <ul>
    <li>Chicago</li>
    <li>Rockford</li>
    </ul>
</li>
</ul>

I did the below select, but it list only the states. Can't find a way to show respective cities:

<?php
$result = mysqli_query($con,"SELECT DISTINCT states,cities FROM table ORDER BY states");
while($row = mysqli_fetch_array($result))
{
  // show here
}
?>
4

3 回答 3

0

states will probably be

$row['states']

cities

$row['cities']
于 2013-07-31T22:07:27.413 回答
0

假设返回的每条数据库记录都包含一个州和一个城市,一种方法是

SELECT states,cities FROM table ORDER BY states, cities

我不确定您是否需要 DISTINCT,除非您可能有重复的记录。这应该给出按州和州内按城市排序的结果。

您可以跟踪看到的最后一个状态的循环,当它发生变化时,关闭最后一个状态的条目 ( </ul></li>)。确保不要一开始就这样做($previousState == '')。启动新状态,输出第一个城市,一直输出城市,直到状态再次发生变化。

于 2013-07-31T23:45:06.977 回答
0

您正在将州和城市获取到数组中,因此您应该尝试打印它们:

while($row = mysqli_fetch_array($result)){
    echo $row['cities']."<br/>";
    echo $row['states']."<br/>";
}

但这仍然不足以为您提供所需的结果,因为查询没有按州对城市进行分组。但对于 php 部分,这是您必须做的。如果您需要有关 sql 的帮助,请告诉我:p

于 2013-07-31T22:12:05.100 回答