我試圖按不同字段升序和降序對數據進行排序。但是,我有4個領域我有不同的MySQL的PDO語句(8個查詢總數):減少僅在ORDER BY字段名稱不同的mysql語句
$stmt1 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field1 DESC");
$stmt2 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field1 ASC");
$stmt3 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field2 DESC");
$stmt4 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field3 ASC");
$stmt5 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field3 DESC");
$stmt6 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field3 ASC");
$stmt7 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field4 DESC");
$stmt8 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field4 ASC");
基於輸入,我挑選合適的語句和綁定並執行它。
if ($sortcode == 1){
$stmt1->bindParam(':categ', $categ, PDO::PARAM_STR);
$stmt1->execute();
$fetched = $stmt1->fetchAll(PDO::FETCH_ASSOC);
} else if ($sortcode == 2){
$stmt2->bindParam(':categ', $categ, PDO::PARAM_STR);
$stmt2->execute();
$fetched = $stmt2->fetchAll(PDO::FETCH_ASSOC);
} else if ($sortcode == 3){
$stmt3->bindParam(':categ', $categ, PDO::PARAM_STR);
$stmt3->execute();
$fetched = $stmt3->fetchAll(PDO::FETCH_ASSOC);
}
//repeat the block 5 more times, for a total of 8
這看起來並不正確。由於select語句僅在字段名稱和desc/asc中有所不同,是否有更好的方法來獲取$sortcode
並壓縮後面的代碼?
我想我可以更具體地說出這個問題:有沒有一種方法我可以有一個單一的語句/單個pdo語句動態地綁定字段名稱和asc/decs?
+1它很容易添加排序列,並且沒有列號 - yikes – Fedearne 2009-11-06 19:55:43
這是一個好主意,但是**它不能解決仍然有8個不同pdo語句的大問題。因此,對於每個選項,當涉及到綁定時間時,我仍然需要調用那個與衆不同的命名查詢並進行綁定和執行。所以主代碼(我上面的8個塊)仍然是相同的,沒有減少。儘管這不是我所要求的,但儘管如此, – Chris 2009-11-06 20:13:30
我已編輯回覆,提供一些進一步的解釋,說明它如何解決您的問題。 – novalis 2009-11-06 20:43:39