您的代码失败,因为$filter
是 MySQLi 结果资源,而不是数组。实际上,这最好通过两个表之间的简单内部连接来完成。如果 aProductID
中不存在Orders
,则INNER JOIN
首先将其从结果集中排除。
$sql = "
SELECT Products.*
FROM
Products
INNER JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
相反,如果您想检索所有,Products
并且只是指示它是否具有活动订单,请使用 aLEFT JOIN
并测试列表Orders.ProductID
中是否为空SELECT
:
$sql = "
SELECT
Products.* ,
/* No orders will print 'no-orders' in a pseudo column called has_orders */
CASE WHEN Orders.ProductID IS NULL THEN 'no-orders' ELSE 'has-orders' AS has_orders
FROM
Products
LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
// And the column $row['has_orders'] will tell you if it has any...
在这种情况下,您可以在行集上循环测试它是否有订单:
foreach ($results as $r) {
if ($r['has_orders'] == 'has-orders') {
// this has orders
}
else {
// it doesn't...
}
}