Thursday, January 21, 2016

PHP Arrays: How To Save an Array in PHP from Checkbox

Good day guys! This article contains a tutorial on how to create an array from a checkbox and save those values in a different rows in your database. I also created a tutorial on how to save several array values from a textbox. If you want to read it, just search it from my blog posts.

Just an overview, an array contains several values unlike an ordinary variable that can only hold a single value at the same time.

There will be cases wherein you are going to get values from checkboxes with same name and save it in different rows in your table. Below is your HTML code with five (5) checkboxes. Each checbox contains different values from A-E. Those values will be saved in the ANSWER table.


<form method="post">
<input type="checkbox" class="form-control" name="answer[]" value="A">
<input type="checkbox" class="form-control" name="answer[]" value="B">
<input type="checkbox" class="form-control" name="answer[]" value="C">
<input type="checkbox" class="form-control" name="answer[]" value="D">
<input type="checkbox" class="form-control" name="answer[]" value="E">

PHP Code

foreach($answer as $value)
mysqli_query($con,"INSERT INTO answer(letter) VALUES('$value')")or die(mysqli_error());

The php code above will save the array values from the checkbox with the name of answer[] in the answer table. First thing to do is to get the values from the checkboxes on submit using the form method post by assigning it to variable $answer. The $answer contains A,B,C,D,E in just a single variable. Then a foreach loop is used to individually assign each array value to variable $value and save it to the answer table.

Output Saving array values in db

Hope this helps! Have a nice day ahead! ^_^

PHP Arrays: How To Save an Array in PHP from Checkbox

No comments:

Post a Comment