Asim Das
Asim Das

Reputation: 93

sql query using checkbox value

I have a html form where there are two Input fields say Caste (options are SC, ST and OBC) and Direction (options are north, south, east and west). Users will choose the options using check box.

<input name="ct" type="checkbox"  value="SC">SC
<input name="ct" type="checkbox"  value="ST">ST
<input name="ct" type="checkbox"  value="OBC">OBC

<input name="dr" type="checkbox"  value="N">North
<input name="dr" type="checkbox"  value="S">south
<input name="dr" type="checkbox"  value="E">East
<input name="dr" type="checkbox"  value="W">West

I have also a database (name : PEOPLE) with column name Caste , Direction etc.

Now I want to run a sql query based on user's selection. For example

mysql_query("select * from PEOPLE where Caste='option/options selected by user' and Direction= 'option/options selected by user' ")

If user choose one option from each field then it is not a problem for me,

mysql_query("select * from PEOPLE where Caste='$_POST[ct]' and Direction= '$_POST[dr]' ")

but if they use multiple options , then how should I proceed.

Upvotes: 0

Views: 3794

Answers (2)

Kasun Rajapaksha
Kasun Rajapaksha

Reputation: 536

You can use WHERE IN

$caste_string = implode('","', $_GET['ct']);
$caste_string = '"'.$caste.'"';

$dir_string = implode('","', $_GET['dr']);
$dir_string = '"'.$caste.'"';


mysql_query("select * from PEOPLE WHERE Caste IN ($caste_string) AND Direction IN ($dir_string)")

Upvotes: 1

Techy
Techy

Reputation: 2654

Give name attribute to the checkboxes like this

<input type="checkbox" name="caste[]" value="SC" />
<input type="checkbox" name="caste[]" value="ST" />
<input type="checkbox" name="caste[]" value="OBC" />

On you php side you can use function implode to form caste into a string as shown below (considering you are doing a POST)

$caste_id = implode(",",$_POST["caste"]);

Where you read from the database you can transform the value from db to an array like this

$caste_array = explode(",",$row->caste_id);

I hope this helps

Upvotes: 2

Related Questions