Peter Jewicz
Peter Jewicz

Reputation: 666

Best way to handle a range on inputs on a drop down select input?

I'm working on a project where I have a drop down menu that has a range of values as follows:

<select name="value">
  <option value="00000000100">0-100</option>
  <option value="00100001000">100-1000</option>
  <option value="01000010000">1000-10000</option>
  <option value="10000100000">10,000</option>
</select>

This select is part a of a form, that once submitted is going to look for values in a database between the given numbers.

I notice there are a lot of sites that have menus like this, but upon doing some searching, I was unable to find any good descriptions on how to do this.

So, I came up with the above idea to pass the above data, and then do something like this to get my values:

$string = $_POST['value']

$min = substr($string, 0, 5);
$max = substr($string, 5);

Then, I can use my values obtained there in my queries.

My question: is there a better way? This way forces me to add extra markup in my selects, which I don't think is going to cause any issues, but I would still like to know if there is an "accepted" way to achieve the same results. Maybe I was using the wrong terms, but I simply couldn't find anything in a similar vein to what I wanted to achieve.

Upvotes: 0

Views: 71

Answers (2)

cOle2
cOle2

Reputation: 4784

I would use an array to store the data and on the select just keys to the array.

This way the user won't be able to inject and change the data being posted and you can easily use it.

Setup your ranges:

$data = array(1=>array(0,100), 2=>array(101,1000), 3=>array(1000,10000), 4=>array(10000,1000000));

The HTML:

<select name="value">
  <option value="1">0-100</option>
  <option value="2">100-1000</option>
  <option value="3">1000-10000</option>
  <option value="4">10,000+</option>
</select>

The receiving page:

if (isset($_POST['value'], $data[$_POST['value']])) {
   $min = $data[$_POST['value']][0];
   $max = $data[$_POST['value']][1];
} else {
   //valid range not submitted
}

© Prix

Upvotes: 0

AbraCadaver
AbraCadaver

Reputation: 79014

Not sure about a "best" way, but if you use the 0-100 style then just:

list($min, $max) = explode('-', $_POST['value']);

For the 10,000 option, 10,000 will be the $min and $max will not exist.

Upvotes: 2

Related Questions