Reputation: 259
I have a select box where i pass the value through ajax to a mysql statement. I need to make it a bit more intelligent, so i dont have to hardcode all the values from the select box
The HTML select box is:
<select>
<option value="value1">something</option>
<option value="value2">somethingElse</option>
</select>
I pass the value through ajax with:
var opts = [];
$selectboxes.each(function(){
opts.push($(this).val());
})
In my php file i use the value to filter a SQL select statement:
if (in_array("something", $opts)){
$where .= " AND region = 'something'";
}
If the user selects option 1 with the value value1
the php file should change to something like
if (in_array("VALUE1", $opts)){
$where .= " AND region = 'VALUE1'";
}
Upvotes: 0
Views: 125
Reputation: 1508
If you have multiple values in something variable then you probably store those values in an array and using array_intersect you can achive desired result.
<?php
$opts = Array ('value1','value2','value3','value4'); //select box values which your are passing from ajax call
$somethingArray = Array('something', 'value1','value4'); //value that you need to match / compare
$result = array_intersect($opts, $somethingArray);
$where = '';
foreach ($result as $key => $value) {
$where .= " AND region = '".$value."'";
}
echo $where; //Output=> AND region = 'value1' AND region = 'value4'
?>
Upvotes: 0
Reputation: 32354
Use the IN option of where and array_intersect to select only the values that we find in $isarray
$isarray= array("something","somethingElse",....)
$is = array_intersect($ops,$isarray)
$where .= " AND region IN ".$is
Note: properly sanitize your $opts so you don't have sql injection
Upvotes: 1