简体   繁体   English

mysql PHP查询问题

[英]mysql PHP query question

Ok, i have a problem here... 好的,我在这里有问题...

I am sending values of drop down lists via ajax to this PHP file. 我正在通过ajax将下拉列表的值发送到此PHP文件。

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... 现在,我想使用这些值搜索mysql数据库,但只有在将这些值设置为某些值的情况下,我才设法这样做。

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... 现在,如果用户没有选择任何“ price_from”或“ year_from” ...该字段是可选的,因此,如果用户未输入任何“ price from”或“ year from”,则用户希望显示所有汽车...

Do I have to write a query statement for each case or is there another way? 我是否必须针对每种情况编写查询语句,还是有其他方法?

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. 我做了与davethegr8类似的事情,除了我将条件放在一个数组中,然后在最后内爆,这样我就不必担心要添加哪些条件以及是否需要添加额外的AND。

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);
}

You could simply detect which parameters are missing in your PHP code and fill in a suitable default. 您可以简单地检测PHP代码中缺少哪些参数,并填写适当的默认值。 eg 例如

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

您可以构建查询,仅当变量与“”不同时才添加“ where”部分。

or if you're using mysql 5.x, you can also use subselects: 或者,如果您使用的是mysql 5.x,则还可以使用子选择:

http://dev.mysql.com/doc/refman/5.0/en/subqueries.html 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. 例如,使用Firebug注入一些鲜美的sql并不重要。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM