我使用以下查询来填充表格:
$result = mysql_query("SELECT vendor, part_number, machine, Sum(q_received) AS received, Sum(q_rejected) AS rejected FROM qa_parts Group by vendor, part_number, machine Order by vendor ASC");
我希望供应商对结果进行分组,然后在供应商下显示来自它们的所有部件及其详细信息。
这就是我需要做的事情:
http://www.gen-techno.com/images/old.jpg
现在正在做什么:
http://www.gen-techno.com/images/new.jpg
正如您所看到的那样,供应商O.P.S产品的零件没有在该供应商下分组,就像Allied Electronics的上述示例中的零件一样。
我现在的表格代码:
while($row = mysql_fetch_array($result))
{
echo "<h4>" . $row['vendor'] . "</h4>[fancy_table]<table>
<tr>
<th>Part Number</th>
<th>Quantity Received</th>
<th>Quantity Rejected</th>
<th>Machine</th>
</tr>";
echo "<tr>";
echo "<td>" . $row['part_number'] . "</td>";
echo "<td>" . $row['received'] . "</td>";
echo "<td>" . $row['rejected'] . "</td>";
echo "<td>" . $row['machine'] . "</td>";
echo "</tr>";
echo "</table>[/fancy_table]";}
答案 0 :(得分:2)
在每个循环中,您必须决定是否该抽出标题 - 您将列出新的供应商。如果不是新供应商,您仍然会列出您绘制最后一个标题的部分,因此您不需要标题或结束表格。
$current_vendor = false;
while($row = mysql_fetch_array($result)) {
// listing a new vendor? Output the heading, start the table
if ($row['vendor'] != $current_vendor) {
if ($current_vendor !== false)
echo '</table>[/fancy_table]'; // if we're changing vendors, close the table
echo '
<h4>'.$row['vendor'].'</h4>[fancy_table]
<table>
<tr>
<th>Part Number</th>
<th>Quantity Received</th>
<th>Quantity Rejected</th>
<th>Machine</th>
</tr>
';
$current_vendor = $row['vendor'];
}
// output the row of data
echo '<tr>
<td>'.$row['part_number'].'</td>
<td>'.$row['received'].'</td>
<td>'.$row['rejected'].'</td>
<td>'.$row['machine'].'</td>
</tr>
';
}
echo '</table>[/fancy_table]'; // close the final table
另一方面,您应该开始更新此代码以使用PDO。显然,您正在更新过去存在的东西......让PDO成为此更新的一部分。 mysql_*
函数正在弃用,很快它们就会消失。
PDO并不难过渡到现在,当你已经处理过的事情比以后更加容易,当你面对“它没有破坏,不要修复它”时“问题。
使用卓越的PDO DBA方法快速查看代码:
$pdo = new PDO("mysql:host=localhost;dbname=database", '-username-', '-password-');
$sql = '
SELECT
vendor,
part_number,
machine,
SUM(q_received) AS "received",
SUM(q_rejected) AS "rejected"
FROM
qa_parts
GROUP BY
vendor,
part_number,
machine
ORDER BY
vendor ASC
';
$statement = $pdo->prepare($sql);
$statement->execute();
while ($order = $statement->fetch()) {
/* Put your table code here! */
}
<强>文档强>
foreach
- http://php.net/manual/en/control-structures.foreach.php mysql_query
(已弃用) - http://php.net/manual/en/function.mysql-query.php PDO::prepare
- http://www.php.net/manual/en/pdo.prepare.php PDOStatement::fetch
- http://www.php.net/manual/en/pdostatement.fetch.php PDOStatement::execute
- http://www.php.net/manual/en/pdostatement.execute.php 答案 1 :(得分:0)
您需要将循环分为两部分。第一部分检查您是否有新的/不同的供应商,并设置“外部”设置。然后是内部部分,它会淘汰供应商的部件。
e.g。
$prev_vendor = null;
while($row = ...) {
if ($row['vendor'] != $prev_vendor) {
... new vendor stuff ...
$prev_vendor = $row['vendor']; // update vendor for next iteration
}
... dump this row's machine data ...
}