获取数据库中相似行的数量并在表单中单独显示它们

时间:2012-02-08 22:39:07

标签: mysql arrays forms

我在数据库中有一个用户表,用户将表单输入数据库。这包括多个单选按钮。我想要它,所以相应的表单条目旁边会显示类似单选按钮的数量。

有8个无线电选择,我有一个可行的解决方案,虽然这不是理想的:

    mysql_select_db($database_name, $db) or die(mysql_error());

$query1 = "SELECT streamnumber, COUNT(id) FROM users WHERE streamnumber = 'Stream1' GROUP BY streamnumber ORDER BY streamnumber "; 
$result1 = mysql_query($query1) or die(mysql_error());

$query2 = "SELECT streamnumber, COUNT(id) FROM users WHERE streamnumber = 'Stream2' GROUP BY streamnumber ORDER BY streamnumber "; 
$result2 = mysql_query($query2) or die(mysql_error());

$query3 = "SELECT streamnumber, COUNT(id) FROM users WHERE streamnumber = 'Stream3' GROUP BY streamnumber ORDER BY streamnumber "; 
$result3 = mysql_query($query3) or die(mysql_error());

$query4 = "SELECT streamnumber, COUNT(id) FROM users WHERE streamnumber = 'Stream4' GROUP BY streamnumber ORDER BY streamnumber "; 
$result4 = mysql_query($query4) or die(mysql_error());

$query5 = "SELECT streamnumber, COUNT(id) FROM users WHERE streamnumber = 'Stream5' GROUP BY streamnumber ORDER BY streamnumber "; 
$result5 = mysql_query($query5) or die(mysql_error());

$query6 = "SELECT streamnumber, COUNT(id) FROM users WHERE streamnumber = 'Stream6' GROUP BY streamnumber ORDER BY streamnumber "; 
$result6 = mysql_query($query6) or die(mysql_error());

我对每个单选按钮进行了单独查询,然后使用此逻辑显示信息:

    <?php 
    while($row = mysql_fetch_array($result1)){

                    echo "There are ". $row['COUNT(id)'] ." ". $row['streamnumber'] ." items.";
                    echo "<br />";


        } ?>
<input style="width:5px;" type="radio" name="streamnumber" value="Stream1" id="StreamDates_0">  
<label>Stream 1 - Module 1 + 2 - 21st - 23rd March, Module 3 - 19th - 20th April, Module 4 - 15th - 16th May 4</label>

这样我可以使用每个计数和名称,因为查询指定了streamnumber。我想知道是否有更简单的方法来做到这一点?我认为这将与更复杂的阵列有关,但我不能完全指责它。

1 个答案:

答案 0 :(得分:1)

你不能只运行1个查询吗?

$query = "SELECT streamnumber, COUNT(id) AS cnt FROM users 
 WHERE streamnumber IN ('Stream1', 'Stream2', 'Stream3',
 'Stream4', 'Stream5', 'Stream6') 
 GROUP BY streamnumber ORDER BY streamnumber "; 
$result = mysql_query($query) or die(mysql_error());
$my_array=array();
while($row = mysql_fetch_array($result1))
{
  $my_array[$row["streamnumber"]] = $row["cnt"];
}
// now $my_array["Stream1"] contains count of 'Stream1'