pdo binding asc/desc order dynamically
Let's say I have 2 pdo statements that differ only in order (asc vs. desc)
$stmt1 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field1 开发者_如何学CDESC");
$stmt2 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field1 ASC");
Is there a way I can bind ASC/DESC dynamically so I can have only 1 stmt
$order = "ASC"; //or "DESC"
$stmt = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field1 order=:order");
$stmt->bindParam(':order', $order, PDO::PARAM_STR);
no. parameters are automatically quoted, and ASC/DESC shouldn't be quoted. this is the same reason that table and column names can't be parameters.
What I did was create a variable in $_session called "task_order" and set it to 0 by default. Then, in the sql statement I call a private function/switch statement that determines if ASC or DESC should be added to the sql statement. If it's 0, then it returns "ASC" and sets "task_order" to 1. If it's 1, it does the opposite. So it works like a "toggle" mechanism.
I understand this is an old question/topic, but I stumbled upon it be searching, so maybe someone else will as well. If you have a better idea, please share!
EDIT:found some old code:
$sql = "SELECT * FROM tasks WHERE owner = ? ORDER BY priority " . $this->check_sort_status() . "";
and the method that I call is :
public function check_sort_status() {
switch ($_SESSION["asc"]) {
case 0:
$_SESSION["asc"] = 1;
return "ASC";
case 1:
$_SESSION["asc"] = 0;
return "DESC";
}
精彩评论