mysql PHP行数+百分比

时间:2012-03-13 19:31:02

标签: php mysql

我有一张简单的表格:

-- ----------------------------
CREATE TABLE `clothes` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `shirt` text NOT NULL,
  `color` varchar(255) NOT NULL,
  PRIMARY KEY (`id`);
-- ----------------------------

示例表内容:

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

我的最终目标是将结果提供为以下格式:

<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>

导致(带有舍入百分比):

  <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>

我一直在尝试各种代码,但没有什么能让我成为我需要的地方:

 <?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 />";
}

    ?>

这让我几乎有了这个 - 但我需要能够将结果分开插入HTML:

There are 4 white items.
There are 4 yellow items.
There are 2 blue items.

任何想法都将不胜感激。感谢。

1 个答案:

答案 0 :(得分:4)

以下是您可以做的事情:

SELECT color, COUNT(*) AS color_count FROM clothes GROUP BY color

您应该得到如下结果:

color    color_count
yellow   7
red      1
white    9

这些数据足以让您计算总行数(所有color_count值之和)及其百分比(只需将它们除以)。

所以,在php中你会有类似的东西:

$query = "SELECT color, COUNT(*) AS color_count FROM clothes GROUP BY color";
$result = mysql_query($query);
$values = array();
$pct = array();
$total = 0;

while ($row = mysql_fetch_assoc($result)) {
    $values[$row["color"]] = $row["color_count"];
    $total += $row["color_count"];
}

foreach($values as $key => $value) {
    $pct[$key] = $value/$total;
}

所以,你最终得到的是,$values["yellow"]会给你黄色衣服的数量,$pct["yellow"]*100会给你黄色衣服的百分比。