pdo动态绑定asc/desc顺序

发布于 2024-08-10 12:26:31 字数 515 浏览 3 评论 0原文

假设我有 2 个仅顺序不同的 pdo 语句(asc 与 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");

有没有办法可以动态绑定 ASC/DESC,这样我就只能有 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);

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 DESC");
$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);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

晨曦÷微暖 2024-08-17 12:26:32

不。参数会自动加引号,ASC/DESC 不应加引号。这与表名和列名不能作为参数的原因相同。

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.

思念绕指尖 2024-08-17 12:26:32

我所做的是在 $_session 中创建一个名为“task_order”的变量,并将其默认设置为 0。然后,在 sql 语句中,我调用一个私有函数/switch 语句来确定是否应将 ASC 或 DESC 添加到 sql 语句中。如果为 0,则返回“ASC”并将“task_order”设置为 1。如果为 1,则执行相反的操作。所以它的工作原理就像一个“切换”机制。

我知道这是一个老问题/主题,但我在搜索时偶然发现它,所以也许其他人也会这样做。如果您有更好的想法,请分享!

编辑:发现一些旧代码:

$sql = "SELECT * FROMtasks WHEREowner=?ORDERBYpriority" 。 $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";
}  

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";
}  
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文