I am having some trouble figuring out how to get my array that I got from an input field. so what works and i get my array showing on which ones I have chosen my problem is that when I add the $selagegroup into the sql INSERT it only shows me the last one that is checked and not all that are checked. i am still somewhat new to sql and php so any help would be greatly appreciated here is my HTML and PHP code
<label for="agegroup" id="agegroup"> What ages do you interact with? <input type="checkbox" name="age[]" class="ages" id="kids" value="kids"> Ages 0-10 <input type="checkbox" name="age[]" class="ages" id="teens" value="teens"> Ages 11-19 <input type="checkbox" name="age[]" class="ages" id="twentys" value="twenties"> Ages 20-29 <input type="checkbox" name="age[]" class="ages" id="thirtys" value="thirties"> Ages 30-39 <input type="checkbox" name="age[]" class="ages" id="fourtys" value="fourties"> Ages 40-49 <input type="checkbox" name="age[]" class="ages" id="fiftys" value="fifties"> Ages 50-59 <input type="checkbox" name="age[]" class="ages" id="sixtyplus" value="sixtyplus"> Ages 60+ </label>
here is the php I have used to get the array shown:
if (isset($_POST['age']) && $_POST['age'] !== '') { $vagegroup = $_POST['age']; foreach($_POST['age'] as $selagegroup){ echo $selagegroup.'<br>'; } } else { $vagegroup = ''; }
I have also tried adding the foreach loop to the sql insert but that just shows “”,””,””, for every field in the checkbox and i dont know what to do any help will be greatly appreciated, Even tho when i just echo the array it works and shows everything that is checked. if someone could explain and help thank you 🙂
EDITED ::: I forgot to add this my insert statement overall has like 30 differnt fields as this is a long form but this is how i did for the age group and it only shows the last selected value
$sql_insert = "INSERT INTO influencers (inf_ages) VALUES ('$selagegroup')";
Advertisement
Answer
If you expect an array of responses, you can serialize or json_encode the data before you save it to the database, provided that the db column is at least VARCHAR of a decent length
I also suggest checking that it is an array and confirming you’re retrieving the input you desire (always validate!), then simply pass through one of the aforementioned methods rather than looping to create a string — this takes up more resources than serializing or encoding.