我试图按不同字段升序和降序对数据进行排序。但是,我有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