1
我被困在一段代碼中,我無法使其工作。我需要幫助。這裏是:使用PHP和SQL進行多個選擇(HTML)搜索
我想用幾個多選,PHP和SQL構建一個搜索。在爲例,我將使用02(二)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 -->
現在,我提交的形式,它是在同一個頁面的形式PHP:
<?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);
?>
在這裏,我卡住了!我不知道如何同時從兩個多選中捕獲多個值並將它們解析爲SQL搜索。
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)
我能勝任,通過治療multiselects一個接一個,但是這將在年底成爲代碼一大塊,也將是非常難以理解。
我希望你們能理解我,我真的需要幫助!
在此先感謝!
PS .:代碼捕捉每個多選中的第一個選項,但它不支持其他選項。