【问题标题】:PHP MySQL- Change Where statement according to GET variablesPHP MySQL-根据GET变量更改Where语句
【发布时间】:2023-03-11 12:55:01
【问题描述】:

您好,我有一张表,我想在这张表上应用 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 个查询,比如首先我想获取 product = car 的所有结果

查询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;

提前谢谢...

【问题讨论】:

  • 你试过了吗?看起来不错。
  • @Qirel 是的,我从几个小时就开始尝试......它不工作不知道为什么......
  • 然后调试它。您知道,我们无权访问您的计算机,也无法运行您的程序来查看它为什么不起作用。
  • "not working" 并没有真正描述问题,让我们很难为您提供帮助 ;-) 不起作用 如何 ?
  • @AlessandroMaglioccola 实际上我写的是 $where="product='car'" 而不是 $where="WHERE product='car'"...

标签: php mysql sql if-statement


【解决方案1】:

您将使用准备好的语句和绑定变量。至于升序或降序,这并不容易,因为 ASC 和 DESC 是关键字,绑定变量只能用于列值,不能用于关键字。但是,降序排序价格与按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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-01
    • 2021-04-11
    • 2016-06-14
    • 2017-09-06
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多