Thursday, January 21, 2016

PHP ARRAYS: How To Save Multiple Arrays in Database

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

I have encountered saving a single array from a checkbox into the database. The code is similar with the code below. The only difference is to omit the $i=0; and $letter[$i]. But in this article, I'll be dealing with multiple arrays. I have here several input controls, specifically a textbox that are arrays. How are you going to know if a certain input control is an array or contains an array value? Find the name and check if it has a bracket [] after it.

The code below contains two (2) arrays, namely the letter and the choice. We will save it like this.

Output Save Multiple Arrays

So you need to create an ANSWER table with letter and choice column names. I will further explain the HTML code below. The first two (2) textboxes with the name of letter[] have a fix value of A and B and are set to readonly. In short, values are fixed and cannot be altered or the user cannot input a value to it.

The third and fourth textboxes with the name of choice[] does not have an initial value and is not set to readonly. Therefore, a user can provide an input to it.

HTML Code Multiple Arrays

<form method="post">
<div class="col-md-1">
<input type="text" class="form-control" value="A" name="letter[]" readonly>
<input type="text" class="form-control" value="B" name="letter[]" readonly>
<div class="col-md-4">
Column B
<input type="text" class="form-control" name="choice[]">
<input type="text" class="form-control" name="choice[]">

PHP Code Saving Multiple Arrays

foreach($choice as $c) 

mysqli_query($con,"INSERT INTO answer(choice,letter) VALUES('$c','$letter[$i]')")or die(mysqli_error());

Take a look at the PHP code above. It contains two (2) variables that stores the values from two (2) textboxes the choice and letter. Next is to initialize the value of the index $i to zero (0) (this will be used to access the values of arrays later on. Indexes starts with zero (0) thats why we start at zero). Next is to get each value of arrays and store it in our ANSWER table using the foreach loop. We use the $choice and save each value to $c and insert it in our table. $letter[$i] is used to access each array value from the $letter. We accessed it using their index like $letter[0] for the first value, followed by $letter[1]. $i++ will increment the index from 0 to 1 or depending on the number of values found in the variable found inside your foreach loop.

For any questions, you can post a comment below. Good day and have a nice day! ^_^

PHP ARRAYS: How To Save Multiple Arrays in Database

No comments:

Post a Comment