MySQL & PHP Get Num of Records for Each Type
I have a MySQL database table which holds 6 types of records I need to get the total number of records for each of the types and then create a variable for each one of the results so for example
wt = 3 spv = 33 shw = 78
and so on..
I开发者_运维技巧 have written this code
$tquery = "SELECT equipment, COUNT(id) AS num FROM contract GROUP BY equipment";
$tresult = mysql_query($tquery) or die(mysql_error());
while($trow = mysql_fetch_array($tresult)){
echo "There are ". $trow['COUNT(id)'] ." ". $trow['equipment'] ." items.";
echo "<br />";
}
The reason for needing a variable for each type is that I need to work out a percentage value to show this data in a chart, I have written this code and it works fine as long as I have the correct data from the table.
Any help would be awesome thanks
Firstly, where you're referencing $trow['COUNT(id)']
, this is incorrect; it should be coming back to you with the name num
(as defined in your SQL query), so you should actually be using $trow['num']
.
Now to store your totals:
Create an array to contain your totals. Lets call it $total
. Define it as an empty array outside the while
loop:
$total = array();
Then inside the loop, assign a new element for the $total
array containing the equipment type as the key, and the count as the value:
$total[$trow['equipment']] = $trow['num'];
When the loop is finished, you should then have an array containing all the totals, which you can perform calculations on. PHP provides you with the array_sum()
and count()
functions (among plenty of other handy functions) which should be enough to get you started with working out averages and percentages.
hope that helps.
Try something like :
$tquery = "SELECT equipment, COUNT(id) AS num FROM contract GROUP BY equipment";
$tresult = mysql_query($tquery) or die(mysql_error());
while ($tabl = mysql_fetch_array($tresult)){
echo "There are " . $tabl['num'] . " of " . $tabl['equipment'] . ".<br />";
}
精彩评论