vendredi 23 décembre 2016

PHP MySQL- Change Where statement according to GET variables

Hi i have a table and i want to apply 4-5 sql select queries on this table

Table

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

I want to apply 4-5 queries on this table like First i want to fetch all results where product = car

Query1:

SELECT * FROM Table WHERE product='car'

URL:  http://ift.tt/2hZfJOx

Output:

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:  http://ift.tt/2hOT49y

Output:

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:  http://ift.tt/2hZ66iP

Output:

id     name      product       price

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

Is it possible to declare an if else statement in advance and use a variable in sql statement and write select statement once.

Like

$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"
  }
  ------
  ------
  ------
}

Query be like:

SELECT * FROM Table $where;

Thanks in advance...

Aucun commentaire:

Enregistrer un commentaire