I have a simple table:
-- ----------------------------
CREATE TABLE `clothes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`shirt` text NOT NULL,
`color` varchar(255) NOT NULL,
PRIMARY KEY (`id`);
-- ----------------------------
Sample table content:
id shirt color
1 long white
2 short yellow
3 long blue
4 long blue
5 long white
6 short white
7 short white
8 long yellow
9 long yellow
10 short yellow
My FINAL GOAL is to feed the results into this format:
<ul>
<li>Total Rows: <?php echo $totalRows; ?></li>
<li>total yellow count: <?php echo $yellowCount; ?></li>
<li>total yellow percent: <?php echo $yellowPercentage; ?></li>
<li>total blue count: <?php echo $blueCount; ?></li>
<li>total blue percent: <?php echo $bluePercentage; ?></li>
<li>total white count: <?php echo $whiteCount; ?></li>
<li>total white percent: <?php echo $whitePercentage; ?></li>
</ul>
Resulting in (with rounded percentages):
<ul>
<li>Total Rows: 10 </li>
<li>total yellow count: 4</li>
<li>total yellow percent: 40%</li>
<li>total blue count: 2</li>
<li>total blue percent: 20%</li>
<li>total white count: 4</li>
<li>total white percent: 40%</li>
</ul>
I’ve been experimenting with various code but nothing has gotten me where I need to be:
<?php
$con = mysql_connect("localhost","root","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("inventory", $con);
// Make a MySQL Connection
$query = "SELECT color, COUNT(color) FROM clothes GROUP BY color";
$result = mysql_query($query) or die(mysql_error());
// Print out result
while($row = mysql_fetch_array($result)){
echo "There are ". $row['COUNT(color)'] ." ". $row['color'] ." items.";
echo "<br />";
}
?>
That gets me almost there with this — but I need to be able to separate the results for inserting into HTML:
There are 4 white items.
There are 4 yellow items.
There are 2 blue items.
Any ideas would be appreciated. THANKS.
Here is what you could do:
You should get a result like:
This data should be enough for you to compute the total number of rows (a sum of all the
color_countvalues) and their percentage (just divide them).So, in php you’ll have something like:
So, in the end what you have is,
$values["yellow"]will give you the number of yellow clothes, and$pct["yellow"]*100will give you the percentage of clothes that is yellow.