wobsoriano
wobsoriano

Reputation: 13462

PHP pass value of checkbox to query

Hello so I have this form with 3 checkbox:

<form action="send.php">
<input type="checkbox" name="txt_group" value="CID">CID
<input type="checkbox" name="txt_group" value="OSDS">OSDS  
<input type="checkbox" name="txt_group" value="SGO">SGO
<input type="submit">
</form>

And in my send.php I have this code:

$stmt = $dbc->query("SELECT * FROM tblcontactlist WHERE contactGroup=:cgroup");
$stmt->bindParam(':cgroup', $_POST['txt_group']);
$stmt->execute();

I think that if I check only 1 checkbox, this will work. But what if I select 2-3 checkbox? Will this query still work?

Upvotes: 1

Views: 966

Answers (4)

Glenn John Ogapong
Glenn John Ogapong

Reputation: 51

yes, a square bracket for the variable name is necessary if you are to post values as an array.. this name="text_group[]" is correct ..

Upvotes: 0

Sougata Bose
Sougata Bose

Reputation: 31749

You cant have same name for multiple inputs if it is not an array, else they will be overwritten by the last one. Try with -

<form action="send.php">
<input type="checkbox" name="txt_group[]" value="CID">CID
<input type="checkbox" name="txt_group[]" value="OSDS">OSDS  
<input type="checkbox" name="txt_group[]" value="SGO">SGO
<input type="submit">
</form>

With php an example query will be -

$values = implode("','", $_POST['txt_group']);
$values = $mysqli->real_escape_string($values);
"SELECT * FROM tblcontactlist WHERE contactGroup IN ('" . values . "')"

Upvotes: 4

Lal krishnan S L
Lal krishnan S L

Reputation: 1745

On your code you are given same name for all checkbox like this

<input type="checkbox" name="txt_group" value="CID">CID

Try to change name as array like

<input type="checkbox" name="txt_group[]" value="CID">CID
<input type="checkbox" name="txt_group[]" value="OSDS">OSDS  
<input type="checkbox" name="txt_group[]" value="SGO">SGO

and print it on server side using

print_r($_POST['txt_group']);

Upvotes: 1

Gary Liu
Gary Liu

Reputation: 13918

change the input name to array

<input type="checkbox" name="txt_group[]" value="CID">CID

then $_POST['txt_group'] get an array list of you checked

Upvotes: 2

Related Questions