如何在查询返回结果时有条件地运行PHP代码?

时间:2017-07-01 08:43:57

标签: php

我希望有人可以帮助我找到构建此代码的最佳方法。

我作为志愿者经营一个石油俱乐部,如果没有特定油类型的报价,那么由于在代码中进一步查询中使用了空变量,页面会失败。

理想情况下,如果查询没有返回任何结果,我希望默认为$win_supplier_red_id = 0,但我不确定捕获它的最佳方法以及代码中最佳位置。

$sql2a= "Select Quote_id from tbl_quote where (select min(quote_price) as best_red from tbl_quote where fuel_type_id =2 AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ) AND quote_price > 10) = quote_price AND timestamp > date_sub( NOW(), INTERVAL 7 DAY ) Order by timestamp Limit 1";
$stmt2a = $db->prepare($sql2a);
$stmt2a->execute();
$res2a = $stmt2a->fetchObject();
$best_red_quote = $res2a->Quote_id;
$sql2= "SELECT qt.quote_id, ft.fuel_type_id, ft.fuel_name, st.supplier_id, st.company_name as company_name, st.email, qt.supplier_id, qt.timestamp, qt.fuel_type_id, min( qt.quote_price ) AS best_red
FROM tbl_quote qt
INNER JOIN `tbl_suppliers` st ON qt.supplier_id = st.supplier_id
INNER JOIN `tbl_fuel-type` ft ON qt.fuel_type_id = ft.fuel_type_id
WHERE qt.Quote_id = $best_red_quote
Order by timestamp";
$stmt2 = $db->prepare($sql2);
$stmt2->execute();
$res2 = $stmt2->fetchObject();
$best_red = $res2->best_red;
$winning_supplier_red = $res2->company_name;
$win_supplier_red_id = $res2->supplier_id;

1 个答案:

答案 0 :(得分:0)

$stmt2 = $db->prepare($sql2);
$stmt2->execute();
$res2 = $stmt2->fetchObject();

if (is_object($res2)) {
    $best_red = $res2->best_red;
    $winning_supplier_red = $res2->company_name;
    $win_supplier_red_id = isset($res2->supplier_id) ? $res2->supplier_id : 0;
} else {
     $best_red = '';
     $winning_supplier_red = '';
     $win_supplier_red_id = 0;
}