使用PHP显示Mysql查询组

时间:2013-02-11 18:11:24

标签: php mysql group-by

我想在使用PHP的Mysql查询中显示一个看起来像这样的表:

Vendor Name

Item Not to Drawing     Item Defective    Incorrect Item Received   Other

         9                    2                    3                  5


Vendor Name

Item Not to Drawing     Item Defective    Incorrect Item Received   Other

         2                    4                    5                  7

等。

这是我的代码......

<?php
$con = mysql_connect("localhost","xxx","xxx");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("qa", $con);

$result = mysql_query("SELECT Vendor, Sum(draw), Sum(defective), Sun(received), Sum(other) FROM qa_reports Group by Vendor Order by Vendor ASC");
echo "<table>
<tr>
<th>Item not to Drawing</th>
<th>Item Defective</th>
<th>Incorrect Item Received</th>
<th>Other</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['Sum(draw)'] . "</td>";
  echo "<td>" . $row['Sum(defective)'] . "</td>";
  echo "<td>" . $row['Sum(received'] . "</td>";
  echo "<td'>" . $row['Sum(other)'] . "</td>";
  echo "</tr>";
  }
echo "</table>";
mysql_close($con);
?>

不确定如何将上述结果格式化为这样。

我已经使用CFML做了这个,但我是PHP的新手,无法掌握如何在按字段分组的表中列出结果。

2 个答案:

答案 0 :(得分:2)

您需要为列添加别名,以便在$row数组中引用它们。

SELECT vendor, 
       Sum(draw)      AS draw, 
       Sum(defective) AS defective, 
       Sun(received)  AS received, 
       Sum(other)     AS other 
FROM   qa_reports ...

然后你可以像这样引用它们:

$row['draw'];
...

答案 1 :(得分:2)

SELECT Vendor, Sum(draw) AS sumDraw, Sum(defective) AS sumDefective ...

$row['sumDraw']等。