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

时间:2016-12-23 08:49:58

标签: php mysql sql if-statement

嗨我有一张桌子,我想在这张桌子上应用4-5个sql select查询

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个查询,比如First我想获取所有结果,其中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

QUERY2:

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

QUERY3:

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;

提前致谢...

1 个答案:

答案 0 :(得分: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);