pdo动态绑定asc/desc顺序
假设我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不。参数会自动加引号,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.
我所做的是在 $_session 中创建一个名为“task_order”的变量,并将其默认设置为 0。然后,在 sql 语句中,我调用一个私有函数/switch 语句来确定是否应将 ASC 或 DESC 添加到 sql 语句中。如果为 0,则返回“ASC”并将“task_order”设置为 1。如果为 1,则执行相反的操作。所以它的工作原理就像一个“切换”机制。
我知道这是一个老问题/主题,但我在搜索时偶然发现它,所以也许其他人也会这样做。如果您有更好的想法,请分享!
编辑:发现一些旧代码:
$sql = "SELECT * FROMtasks WHEREowner=?ORDERBYpriority" 。 $this->check_sort_status() 。 “”;
我调用的方法是:
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 :