1 回答

TA貢獻(xiàn)1820條經(jīng)驗(yàn) 獲得超9個贊
問題是,如果你得到一個過濾器,你會用正確的過濾器發(fā)出一個 db-request,但是之后,你仍然在創(chuàng)建默認(rèn)的 db-request 來獲取所有產(chǎn)品。
與其發(fā)出多個數(shù)據(jù)庫請求,不如創(chuàng)建一個。您可以根據(jù)從客戶端獲得的過濾器更改查詢。
替代方案 #1 - 動態(tài)構(gòu)建查詢
像這樣的東西:
$whereConditions = [];
$where = '';
if (isset($_POST["manj300"])) {
// Add this filter
$whereConditions[] = 'price<=300';
}
// Here you can add more conditions, just like the above if-statement
if ($whereConditions) {
// We have a condition, implode and add WHERE
$where = 'WHERE ' . implode(' ', $whereConditions);
}
// Now put the where conditions in your query
$query = "SELECT * FROM tbl_product {$where} ORDER BY id ASC";
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
// Your current code
}
}
?>
這種方法的好處是您可以輕松地在同一查詢中添加更多條件/過濾器。
缺點(diǎn)是代碼變得有點(diǎn)難以閱讀。
替代方案 #2 - 選擇一個預(yù)定義的查詢
您可以定義多個查詢并選擇要使用的查詢:
// This is the "get all" query
$query = "SELECT * FROM tbl_product ORDER BY id ASC";
if (isset($_POST["manj300"])) {
// We have a filter, let's override the default query
$query = "SELECT * FROM tbl_product price<=300 ORDER BY id ASC";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
// Your current code
}
}
?>
這種方法的好處是它非常干凈,易于閱讀和遵循。
缺點(diǎn)是您只能同時(shí)啟用一個過濾器。
- 1 回答
- 0 關(guān)注
- 151 瀏覽
添加回答
舉報(bào)