以下是我目前正在使用的代码的摘录:
假设$product=Onion
& $area=Bulua
。
$crop_query = $db->query(
"SELECT Crop, Price, DateUpdated, Area FROM crops
WHERE Crop = '{$product}'
AND `DateUpdated` = (SELECT max( `DateUpdated` )FROM crops WHERE Crop = '{$product}' )
AND `Area` = '{$area}'");
$result = $crop_query->fetch(PDO::FETCH_OBJ);
$message = "The current price of {$result->Crop} is P{$result->Price}/kg, as of {$result->DateUpdated} in {$result->Area} Market.";
echo $message;
SQL表摘录:
Crop ID Price DateUpdated Area
Onion 1 75 2011-01-26 14:30:00 Cogon
Onion 2 200 2012-02-22 14:30:00 Bulua
然后,上面的代码将成功打印出所需的输出:
“洋葱的当前价格 P200 / kg, 2012-02-22 14:30:00 Bulua 市场。“
然而,当我将$ area的值更改为$area = Cogon
时会抛出错误。我注意到它的优先级仅在DateUpdated
而不是Area
和DateUpdated
。
编辑:澄清以下评论
Bulua
至Cogon
。DateUpdated
在查询中被优先考虑现在正在运作。谢谢你的关注。 :) 我会尽可能地发布另一个答案。
答案 0 :(得分:0)
检查您的数据和查询。如果没有返回任何行,则$result
将为false
,因此您无法$result->Crop
。
你应该这样做:
$result = $crop_query->fetch(PDO::FETCH_OBJ);
if ($result) {
// Returned results, do something ...
}
另外,请考虑将查询简化为:
SELECT Crop, Price, DateUpdated, `Area`
FROM crops
WHERE Crop = '{$product}'
AND `Area` = '{$area}'
ORDER BY DateUpdated DESC
LIMIT 1