开发者

Mysql... a price range within a price range?

I am developing a real estate script. The script has a search option where an user can specify the price range eg. user_price_low to user_price_high and the listings have t开发者_开发知识库o be fetched from a database, which has eg. db_price_high and db_price_low.

I used a BETWEEN statement trying to find the matches,

WHERE price_low BETWEEN '.$_REQUEST['minprice_buy'].' AND '.$_REQUEST['maxprice_buy']

but to my surprise...

If an user has user_price_high = 60 and user_price_low = 20 AND the record has db_price_low = 30 and db_price_high = 120

my query is invalid in this case.

i tried looking at MySql Query- Date Range within a Date Range but does that match what I want?


Chandan, never ever input $_* functions directly into a query. It's an SQL-injection hole.

Change the code to:

$min_price = mysql_real_escape_string($_REQUEST['minprice_buy']);
$max_price = mysql_real_escape_string($_REQUEST['maxprice_buy']);
$query = "SELECT whatever 
          FROM whichever 
          WHERE price_low BETWEEN '$min_price' AND '$max_price' ";
// Dont forget these quotes       ^          ^     ^          ^
// Or mysql_real_escape_string() will not work!.

With regards to your question, change the query to something like:

WHERE '$min_price' BETWEEN price_low AND price_high 
  AND '$max_price' BETWEEN price_low AND price_high

You may also want to consider:

WHERE ('$min_price' BETWEEN price_low AND price_high) 
  OR  ('$max_price' BETWEEN price_low AND price_high)

Here min_price and max_price don't need to both be in the range at all times.

See: How does the SQL injection from the "Bobby Tables" XKCD comic work?


If you want to check if ranges have any common points you should use

WHERE greatest(price_low,user_price_low)<=least(price_high,user_price_high)

If you want to check if user range is in all range you may use
Undefined behaviour for user_preice_low>user_price_high

WHERE user_price_low>=price_low && user_price_high<=price_high


so accourding to what i understand, shouldnt it be

WHERE price_low >= '.$_REQUEST['minprice_buy'].' AND price_high <='.$_REQUEST['maxprice_buy']'

Validate your Input using mysql_real_escape_string(); before using them in the query, dont use $_GET, $_REQUEST, $_POST variables directly in any query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜