Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

checkbox array only returning one result

Tags:

html

forms

php

I have built a form that has a checkbox input array (saving to an array). However, when I POST it and retrieve the results, it only offers the last selection.

<input type="checkbox" value="Friendly" name="quest[9]"> Friendly<br>
<input type="checkbox" value="Attentive" name="quest[9]"> Attentive<br>
<input type="checkbox" value="Enthusiastic" name="quest[9]"> Enthusiastic<br>
<input type="checkbox" value="Understanding" name="quest[9]"> Understanding<br>
<input type="checkbox" value="Well Mannered" name="quest[9]"> Well Mannered<br>
<input type="checkbox" value="Efficient" name="quest[9]"> Efficient<br>
<input type="checkbox" value="Genuine" name="quest[9]"> Genuine<br>

For example, say I chose "Friendly", "Efficient", and "Genuine".

When I POST it over to a PHP document and run

print_r($_POST['quest']);

I only receive

Array ( [9] => Genuine )

back so "Genuine" is the only item I get back. Is there a way to fix this? What have I done wrong?

This is the 9th question on the survey, so changing the name unfortunately is not an option. Is there any way to combine the results to that single array separated by commas? I could always explode on the php side.

like image 836
James Stafford Avatar asked Feb 19 '23 11:02

James Stafford


2 Answers

All your checkboxes have the same name, make them unique

<input type="checkbox" value="Friendly" name="quest[3]"> Friendly<br>
<input type="checkbox" value="Attentive" name="quest[4]"> Attentive<br>
<input type="checkbox" value="Enthusiastic" name="quest[5]"> Enthusiastic<br>
<input type="checkbox" value="Understanding" name="quest[6]"> Understanding<br>
<input type="checkbox" value="Well Mannered" name="quest[7]"> Well Mannered<br>
<input type="checkbox" value="Efficient" name="quest[8]"> Efficient<br>
<input type="checkbox" value="Genuine" name="quest[9]"> Genuine<br>

or use empty square brackets so php will treat the inputs as an array

<input type="checkbox" value="Friendly" name="quest[]"> Friendly<br>
<input type="checkbox" value="Attentive" name="quest[]"> Attentive<br>
<input type="checkbox" value="Enthusiastic" name="quest[]"> Enthusiastic<br>
<input type="checkbox" value="Understanding" name="quest[]"> Understanding<br>
<input type="checkbox" value="Well Mannered" name="quest[]"> Well Mannered<br>
<input type="checkbox" value="Efficient" name="quest[]"> Efficient<br>
<input type="checkbox" value="Genuine" name="quest[]"> Genuine<br>
like image 169
Musa Avatar answered Feb 21 '23 23:02

Musa


use quest[] in name instead of quest[9]. also in php part use this to add multiple choices .

<?php
$quest = implode(',',$_post['quest']);
print_r($quest);
?>

Happy coding!!

like image 33
Gaurav Avatar answered Feb 21 '23 23:02

Gaurav