计算业务类具有相同的值

时间:2014-03-29 10:22:13

标签: php mysql count

<?php
$con = mysql_connect("localhost","root","root");
if (!$con){
die("Can not connect: " . mysql_error());
}
mysql_select_db("mydb",$con);

        //Count all Total of Acc Class with same value Example Restaurant, Hotel
$query = "select acc_class,count(*) as total from mytable group by acc_class";
$result = mysql_query($query); 
$values = mysql_fetch_assoc($result); 
$num_total = $values['total']; 

while($record = mysql_fetch_array($result)){
echo '<br>';
echo "<label>" . $record['acc_class'] . "</label>";
echo "<label>" . $num_total . "</label>";
}   

mysql_close($con);
?>

伙计们请帮助我。我想生产这样的东西。但我不知道如何。

Account Class   Total
-------------  -----------
Hotel            5
Restaurant       2
Club             3
Church           1

我希望有一个页面,其中会显示每个帐户类的总数。请帮忙。

谢谢!

2 个答案:

答案 0 :(得分:1)

请转储$ values:

的var_dump($值);

我猜,问题在于它是数据本身还是数据获取(数组,关联)。

请格式化SQL以提高可读性:

SELECT acc_class, COUNT(*) AS total FROM mytable GROUP BY acc_class;

Count语句是正确的:https://dev.mysql.com/doc/refman/5.7/en/counting-rows.html

解决方案:

$query = "SELECT acc_class, COUNT(*) AS total FROM mytable GROUP BY acc_class";
$result = mysql_query($query); 

echo '<table border="1">';
while($row = mysql_fetch_array($result)) {
   echo '<tr>';
   echo '<td>' . $row['acc_class'] . '</td>';
   echo '<td>' . $row['total'] . '</td>';
   echo '</tr>';
}
echo '</table>';

答案 1 :(得分:1)

//you just need to put the name of the column in quert like COUNT(column_name)


    $con = mysql_connect("localhost","root","root");
    if (!$con){
    die("Can not connect: " . mysql_error());
    }
    mysql_select_db("mydb",$con);
    //data base connection ends here

    //you write a query to fire if you want by order the put "ORDER BY HERE"
    $query = "select acc_class,count(acc_class) as total from mytable group by acc_class";



    //here you fire a query to mysql  
    $result = mysql_query($query);    


    //now put the selected roe in loop and  again and again loop ask for more data to mysql
    while($record = mysql_fetch_array($result)){

    **//here you select all the group in the table**

    echo '<br>';
    echo "<label>" . $record['acc_class'] . "</label>";
    echo "<label>" . $record['total'] . "</label>";


    }   

    //close connection to database
    mysql_close($con);