下拉列表中的每个状态我想要php中每个状态的记录总数

时间:2017-12-12 05:04:52

标签: php mysqli

Table_sup           |
+-------------------+
| supid=>int        |                
| scompany=>varchar | 
| sstate=>varchar   | 
| scity=>varchar    | 
| scat=>varchar     | 

PHP代码

<?php
    include "db_connect.php";  // including configuration file
?>
<form name="frmdropdown" method="post" action="sample.php">
<center>
        <h2 align="center">Select State</h2>
        <strong> Select State : </strong>
<select name="getData">
        <option value="">ALL--(<?php echo "" . $totalusa;?>) </option>
<?php
        $dd_res=mysqli_query($con,"Select DISTINCT sstate, count(sstate) AS state from sup GROUP BY sup.sstate");   
            while($r=mysqli_fetch_row($dd_res))
                { echo "<option value='$r[0]'> $r[0]</option>";

                }
?>
</select>
<input type="submit" name="Select" value="Select"/> 
<br><hr>

结果我得到了

Select State
-------------
| ALL       | 

| CA        | 

| CO        |

| FL        | 

| GA        |

我想要什么

Select State
+-------------------+

| ALL       |  

| CA (472)  | 

| CO  (7)   | 

| FL  (5)   | 

| GA   (45) | 

像这样。下拉列表中的每个状态我想要每个州的记录总数

2 个答案:

答案 0 :(得分:1)

您没有从mysqli结果中获取第二列。请尝试以下。

<?php
        $dd_res=mysqli_query($con,"Select sstate, count(sstate) AS state from sup GROUP BY sstate");   
            while($r=mysqli_fetch_row($dd_res))
                { echo "<option value='$r[0]'> $r[0] ( $r[1] )</option>";

                }
?>

答案 1 :(得分:0)

因为国家/地区可以有多个州,当您加入这些1到1和1到很多时,每个州都可以拥有多个城市。所以你需要独特的状态计数。城市数量已经是国家和州的独特之处,因此不需要区别。国家不是国家城市独有的地方,因此需要与众不同。当然,这假设您需要在每个国家/地区计算唯一状态。

SELECT c.name, count(distinct s.name) as statecount,  count(ci.name) citycount 
FROM countries c,states s,cities ci
WHERE ci.state_id = s.id 
  and s.country_id = c.id 
GROUP BY s.name

考虑以下示例: http://rextester.com/ZGYF56786

How to get count of State and city of country using SQL query from database?