I'm stuck in a piece of code that I can't make it work. I need help. Here it goes:
I want to construct a search with several multiselect, PHP and SQL. In the exemple I'll use 02 (two) multiselects:
<form action="" method="post">
<!-- first select with its options-->
<select name="search[field1]" multiple="multiple">
<option value="All">-- All --</option>
<option value="value11">Value 11</option>
<option value="value12">Value 12</option>
<option value="value13">Value 13</option>
<option value="value14">Value 14</option>
</select>
<!-- second select with its options -->
<select name="search[field2]" multiple="multiple">
<option value="All">-- All --</option>
<option value="value21">Value 21</option>
<option value="value22">Value 22</option>
<option value="value23">Value 23</option>
<option value="value24">Value 24</option>
</select>
<!-- input submit -->
<input type="submit" value="Search" name="submit"/>
</form><!-- \. end form -->
Now, I submit the form to the PHP which it's in the same page as the form:
<?php
#first I check if the form was submitted
if(isset($_POST['submit'])){
#catch the values from the multiple select forms
$mapping = array (
'field1' => 'Name_of_the_table_field_1' ,
'field2' => 'Name_of_the_table_field_2'
);
$stmt = "select * from [DATA_BASE].[dbo].[TABLE] ";
$operator = " AND ";
if (isset($_POST['search'])){
$stmt = $stmt . "where ";
foreach ($_POST['search'] as $key=>$val) {
$stmt .= $mapping[$key] ." =(case when ".$val." ='All' then ".$mapping[$key]." else '".$val."' end)" . $operator;
}
}
var_dump($stmt);
?>
Here, I stuck! I don't know how to catch multiple values from the two multiple select at the same time and parsing them to a SQL search.
E.g.: the search should return sth like "select * from [DATA_BASE].[dbo].[TABLE] where Name_of_the_table_field_1 = (case when Name_of_the_table_field_1 = 'All' then Name_of_the_table_field_1 else 'value11' AND "value12" end) AND Name_of_the_table_field_2 = (case when Name_of_the_table_field_2 = 'All' then Name_of_the_table_field_2 else 'value21' AND "value23" end)
I could handle that by treating the multiselects one by one, but this would become a big chunk of code at the end, also it would be very difficult to understand.
I hope you guys have understood me, I really need help!
Thanks in advance!!!
PS.: the code is catching the first option select in each multiselect, but it's not holding the others.