user188971
user188971

Reputation:

mysql PHP query question

Ok, i have a problem here...

I am sending values of drop down lists via ajax to this PHP file.

Now I want to search a mysql database using these values, which I have managed to do, BUT, only if I set the values to something...

Take a look:

     $query = "SELECT * FROM cars_db WHERE price BETWEEN '$cars_price_from' AND '$cars_price_to' AND year BETWEEN '$cars_year_from' AND '$cars_year_to' AND mileage BETWEEN '$cars_mileage_from' AND '$cars_mileage_to' AND gearbox = '$cars_gearbox' AND fuel = '$cars_fuel'";

now, what if the user doesnt select any "price_from" or "year_from"... The fields are only optional, so if the user doesnt enter any "price from" or "year from", then the user wants ALL cars to show...

Do I have to write a query statement for each case or is there another way?

Upvotes: 1

Views: 131

Answers (4)

David Weinraub
David Weinraub

Reputation: 14184

I do something similar to davethegr8 except I put my conditions in an array and then implode at the end just so I don't have to worry about which conditions got added and whether I need to add extra AND's.

For example:

$sql = "SELECT * FROM car_db";

// an array to hold the conditions
$conditions = array();

// for price
if ($car_price_from > 0 && $car_price_to > $car_price_from) {
    $conditions[] = "(price BETWEEN '$cars_price_from' AND '$cars_price_to')";
}
elseif ($car_price_from > 0) {
    $conditions[] = "(price >= '$cars_price_from')";
}
elseif ($car_price_to > 0) {
    $conditions[] = "(price <= '$cars_price_from')";
}
else { 
    //nothing
}

// similar for the other variables, building up the $conditions array.

// now append to the existing $sql
if (count($conditions) > 0){
    $sql .= 'WHERE ' . implode(' AND ', $conditions);
}

Upvotes: 4

pxl
pxl

Reputation: 1297

or if you're using mysql 5.x, you can also use subselects:

http://dev.mysql.com/doc/refman/5.0/en/subqueries.html

don't forget to validate the input. It's trivial with firebug, for example, to inject some tasty sql.

Upvotes: 0

Rik Heywood
Rik Heywood

Reputation: 13972

You could simply detect which parameters are missing in your PHP code and fill in a suitable default. eg

if (!isset($cars_mileage_to))
    $cars_mileage_to = 500000;

Upvotes: 1

Davide Gualano
Davide Gualano

Reputation: 13003

You can build you query, adding the "where" part only if your variables are different from "".

Upvotes: 0

Related Questions