将信息从列拉取到 for 循环内部



我有一个订单项目,我想在其中实现标签打印。 每个订单必须根据其对象数量显示标签数量。到目前为止,我已经设法用"for"显示数量。

数据库示例:

+-------+-------------+-----+
| order | description | qty |
+-------+-------------+-----+
|   1   |   stickers  |  1  |
|   2   |   posters   |  2  |
|   2   |   tape      |  1  |
|   2   |  (no desc)  |  1  |
+-------+-------------+-----+

到目前为止,我拥有的:

Select SUM(qty) AS pieces FROM mytable WHERE order = '2'");
$total=$row['pieces']; //this correspond to all items on the order.
for ($x = 1; $x <= $row_count; $x++){
echo $order."<br>"; //order number
echo $x."<br>"; //item
echo $total."<br>"; //total items
}

结果:

#order   #item   #total        #order   #item   #total
+-------+-------+-------+      +-------+-------+-------+
posters   |   2   |   1   |   4   |      |   2   |   2   |   4   |
+-------+--- ---+-------+      +-------+-------+-------+
#order   #item   #total
+-------+-------+-------+
tape   |   2   |   3   |   4   |
+-------+-------+-------+
#order   #item   #total
+-------+-------+-------+
(no desc)  |   2   |   4   |   4   |
+-------+-------+-------+

但是我无法显示每个"描述"列的内容。

理想的结果:

#order  #desc #item #total    #order  #desc #item #total
+---+--------+----+----+      +---+--------+----+----+
posters   | 2 | posters|  1 |  4 |      | 2 | posters|  2 |  4 |
+---+--------+----+----+      +---+--------+----+----+
#order  #desc #item #total
+---+--------+----+----+
tape   | 2 |  tape  |  3 |  4 |
+---+--------+----+----+
#order  #desc #item #total
+---+---------+----+----+
(no desc)  | 2 |(no desc)|  4 |  4 |
+---+---------+----+----+

有没有机会得到这个结果? 我正在使用php和mysql。

您可以将总查询与表本身的查询联接起来。

SELECT m.description, m.qty, t.total
FROM mytable AS m
CROSS JOIN (
SELECT SUM(qty) AS total
FROM mytable
WHERE order = 2
) AS t
WHERE order = 2

然后,您可以使用嵌套循环:

$j = 1;
while ($row = $stmt->fetch()) {
echo $row['description'];
for ($i = 1; $i <= $row['qty']; $i++, $j++) {
echo "$order<br>{$row['description']}<br>$j<br>{$row['total']}<br>";
}
}

最新更新