php - 根据条件(desc 或 asc)在 MySQL 查询后添加逗号

标签 php

我正在动态创建搜索查询,基于搜索,我需要使用 des|asc 附加查询。

例如,如果用户单击 bydate,我将附加 order by bydate desc ,如果用户想搜索公司名称,我会再次追加 order by companyname asc 。这是有条件的。

例如,如果查询是

select * from market

如果用户按日期搜索查询就变成了

 select * from market order by bydate desc

如果用户搜索者按公司名称查询变为

现在如果前面的查询包含 ascdesc我需要插入逗号,所以查询变成

select * from market order by bydate desc, companyname

如果我不检查并插入逗号查询就会变成

select * from market order by bydate desc companyname -- without comma

因此根据条件插入逗号

 $query = 'select * from market order by bydate desc';

    if(  ($despos = false) && (  ( strripos($query, 'desc') !=== false && ($despos =  strripos($query, 'desc')) ) ||  ( strripos($query, 'asc') !=== false && ($despos =  strripos($query, 'asc'))  )   ) && $despost !===false   && $despos >(strlen($query)-7)  ) $query.=", ";

但是查询显示以下错误:

( ! ) Parse error: syntax error, unexpected '=' in E:\wamp\www\sugumar\php\1.php on line 5

最佳答案

$query = "select * from market";
$orderBy = array();

如果用户按日期搜索

array_push($orderBy, "bydate desc");

如果用户搜索者通过公司名称查询

array_push($orderBy, "companyname asc");

if(count($orderBy) > 0) {
   $query = $query." order by ".implode(",", $orderBy);
}

关于php - 根据条件(desc 或 asc)在 MySQL 查询后添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43087215/

相关文章:

php - 将 PHP 数组中的相同项目分组并进行计数

PHP/MYSQL : Value 0 if record isn't yet in database

php - 有什么方法可以阻止人们上传带有注入(inject)的 GIF 动图?

php - 带有 for 循环的安全 PDO mySQL SELECT 语句

php - Laravel 5.6 存储链接已存在,但尝试从公共(public)文件夹获取文件时出现 404 错误

PHPUnit:使用来自父类的测试来测试依赖关系

php - 有什么方法可以用 PHP/MySQL 动态创建流程图或 UML?

php - 为什么php artisan make :factory not Generating with a Model

php 两个数组之间的数组匹配

php - 有没有办法使用 mod_rewrite 从我的网站中删除 .html 和 .php 代码?