Pdo binding asc / desc order dynamically

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 DESC");
$stmt2 = $po->prepare("SELECT * FROM tabname WHERE categ=:categ ORDER BY field1 ASC");

Is there a way to bind ASC / DESC dynamically, so I can only have 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);
+3
source share
2 answers

no. parameters are automatically quoted, and ASC / DESC should not be specified. this is the same reason that table and column names cannot be parameters.

+6
source

, , $_session, "task_order", 0. sql private/switch, , ASC DESC sql. 0, "ASC" "task_order" 1. 1, . , "".

, /, , , , - . , , !

EDIT: :

$sql = "SELECT * FROM tasks WHERE owner =? ORDER BY priority". $this- > check_sort_status(). "";

, :

public function check_sort_status() {

 switch ($_SESSION["asc"]) {
    case 0:
        $_SESSION["asc"] = 1;
        return "ASC";
    case 1:
        $_SESSION["asc"] = 0;
        return "DESC";
}  
0

Source: https://habr.com/ru/post/1722160/


All Articles