我会尽力解释这种情况,但我对php和mysql相当新,所以我很生疏。
尝试实现的im特性是一个查询,导致客户购买的“代码”的回声。
我的问题在于,当客户订购多个项目时,每个客户都会获得一个订单号(在示例中:1081),该订单号链接到order_list数据库,该数据库列出了他们已购买的产品。所以在这个例子中,1081订购了3个产品(1,11,14),这在数据库中显示为..
od_id | pd_id
----------------
1081 | 1
1081 | 11
1081 | 14
因此,当我成功查询1081时,它会返回3行结果。这对于这个例子和数量查询都很好,但是当我需要所有三个结果时,我只在最终的sql查询中得到一个结果。
到目前为止,这是我的测试代码:
//Get order IDS
$sqlid = "SELECT pd_id FROM tbl_order_item WHERE od_id = 1081";
$result = mysql_query($sqlid);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlid;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$ids[] = $row['pd_id'];
}
foreach ($ids as $id) {
echo $id . "<br />";
}
//Get order Qtys
$sqlqty = "SELECT od_qty FROM tbl_order_item WHERE od_id = 1081";
$result = mysql_query($sqlqty);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlqty;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$qtys[] = $row['od_qty'];
}
foreach ($qtys as $qty) {
echo $qty . "<br />";
}
//Get Order Codes
$sqlcode = "SELECT od_code FROM tbl_order_code WHERE pd_id = $id LIMIT $qty";
$result = mysql_query($sqlcode);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlcode;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$codes[] = $row['od_code'];
}
foreach ($codes as $code) {
echo $code . "<br />";
}
页面上的当前结果是:
1 //Three results from "pd_id" (What the customer ordered)
11 //
14 //
1 //Three results from "od_qty" (How many the customer ordered
1 //
2 //
YYXY-YYXY-YYXY-YYXW //The first code result with two codes as there was 2 qty for product 14
YYXY-YYXY-YYXY-YYXX //
my test page you can view the above here.
我希望我有道理,基本上我需要最后的“$ sqlcode”查询来处理上一个查询中的所有行,而不仅仅是第一个。
谢谢!
Key:
pd_id //product id
tbl_order_item //ordered items table
od_id //order id
od_qty //quantity of each product
od_code //order codes
tbl_order_code //codes table each code is related to the pd_id
答案 0 :(得分:1)
将最后一个sql包装在foreach中,以便为每个$ id执行它
你应该真正阅读sql连接,因为整个脚本可以作为一个$ sql stmt
foreach ($ids as $id) {
$sqlcode = "SELECT od_code FROM tbl_order_code WHERE pd_id = $id LIMIT $qty";
$result = mysql_query($sqlcode);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sqlcode;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
$codes[] = $row['od_code'];
}
}
这是尝试使用连接(如果有帮助)
// query data
$order_id = 1081;
$sql = "SELECT tbl_order_item.pd_id, tbl_order_item.od_qty, tbl_order_code.od_code FROM tbl_order_item JOIN tbl_order_code ON
tbl_order_code.pd_id=tbl_order_item.pd_id
WHERE tbl_order__item.od_id = $order_id";
$result = mysql_query($sql);
if (!$result) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $sql;
die($message);
}
while($row = mysql_fetch_assoc($result)) {
printf("Order ID: %s - Product ID: %s - Qty: %s - Code: %s<br />", $order_id, $row['pd_id'], $row['od_qty'], $row['od_code']);
}