PHP MySQL- 根据 GET 变量更改 Where 语句

标签 php mysql sql if-statement

您好,我有一个表,我想在这个表上应用 4-5 个 sql 选择查询

表格

id     name      product       price

1      Amit      car           100000
2      Sumit     car           300000
3      Naina     car           250000
4      Ashu      car           125000
5      Sanjay    scooter        40000
6      Rahul     scooter        32000

我想在此表上应用 4-5 个查询,例如首先我想获取产品 = 汽车的所有结果

查询 1:

SELECT * FROM Table WHERE product='car'

URL:  www.example.com/product/car

输出:

id     name      product       price

1      Amit      car           100000
2      Sumit     car           300000
3      Naina     car           250000
4      Ashu      car           125000

查询2:

SELECT * FROM Table WHERE product='car' ORDER BY price

URL:  www.example.com/product/car?sort=plth

输出:

id     name      product       price

1      Amit      car           100000
4      Ashu      car           125000
3      Naina     car           250000
2      Sumit     car           300000

查询 3:

SELECT * FROM Table WHERE product='car' ORDER BY price DESC

URL:  www.example.com/product/car?sort=phtl

输出:

id     name      product       price

2      Sumit     car           300000
3      Naina     car           250000
4      Ashu      car           125000
1      Amit      car           100000

是否可以预先声明一个if else语句,在sql语句中使用一个变量,写一次select语句。

喜欢

$where="WHERE product='car'";

if(isset($_GET['sort'])){
  if(($_GET['sort'])=='plth'){
    $where="WHERE product='car' ORDER BY price"
  }
  elseif($_GET['sort'])=='phtl'){
    $where="WHERE product='car' ORDER BY price DESC"
  }
  ------
  ------
  ------
}

查询如下:

SELECT * FROM Table $where;

提前致谢...

最佳答案

您将使用准备好的语句并绑定(bind)变量。至于升序还是降序这就不太容易了,因为ASC和DESC是关键字,绑定(bind)变量只能用于列值,不能用于关键字。但是,按价格降序排序与按 price * -1 排序相同 :-)

$product = "car";
$order = "DESC";

$pdo = new PDO("mysql:host=localhost;dbname=database", "username", "password");
$stmt = $pdo->prepare("select * " .
                      "from table " .
                      "where product = :product " .
                      "order by price * case when :order = 'DESC' then -1 else 1 end ");
$stmt->bindParam(':product', $product, PDO::PARAM_STR, 12);
$stmt->bindParam(':order', $order, PDO::PARAM_STR);
$stmt->execute();

或者,如果您觉得 CASE WHEN 不可读,请使用

$order = -1;
...
              "order by price * :order ");
...
$stmt->bindParam(':order', $order, PDO::PARAM_INT);

关于PHP MySQL- 根据 GET 变量更改 Where 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41298087/

相关文章:

php - 处理查询字符串参数时的 Codeigniter 缓存问题

mysql - 如何优化没有记录的日期的匹配日期范围表?

php - 合并和分离查询数据

mysql - 如何在 MySQL 中返回数据透视表输出?

mysql - 在 MySQL 中获取日期的最后一秒

sql - 如何用SQL划分两个SELECT语句以获得百分比

javascript - jQuery 错误 : Object doesn't support property or method 'addEventListener'

php - 从 Google map 获取当前缩放级别

php - 数组 - foreach 带来 -> fatal error : Cannot use object of type

MySQL:判断日期是否存在于多个表中