Capture Array Values from Dynamic input Fields using PHP

Well in my previous post, you were able to add multiple dynamic fields using jQuery. In this tutorial, we will collect values from those dynamically generated input fields, which can be displayed on user browser or store in MySql database. Let's assume you have a HTML form with multiple input fields like example shown below. This fields are generated by jQuery code in my previous post.
HTML
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
<form method="post" action="collect_vals.php"> <div class="input_fields_wrap"> <button class="add_field_button">Add More Fields</button> <div><input type="text" name="mytext[]"></div> <div><input type="text" name="mytext[]"></div> <div><input type="text" name="mytext[]"></div> <div><input type="text" name="mytext[]"></div> <div><input type="text" name="mytext[]"></div> </div> </form>
Notice the name attribute mytext[] in input fields? they all have same name. The brackets indicate that the value of such input field will be posted as an array, so another input field means just another value in existing array.

Capture Array Values using PHP

Collecting values from above input fields is pretty simple, take a look at example below. Once the value is captured from input fields, you can output it on the browser. We can directly access array values using index number, but this will cause error if indexed value doesn't exist in array.
PHP
  • 1
  • 2
echo $_POST["mytext"][0]; echo $_POST["mytext"][1];
Another way is using PHP implode(), it converts array into string, separated by commas or any character. Just make sure POST variable is not empty:
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
if(isset($_POST["mytext"]) && is_array($_POST["mytext"])){ $subject = implode(", ", $_POST["mytext"]); echo $text; } /* returns value1, value2, value3 */
You can also iterate POST variable using foreach like so, result is same as above.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
<?php if(isset($_POST["mytext"]) && is_array($_POST["mytext"])){ $capture_field_vals =""; foreach($_POST["mytext"] as $key => $text_field){ $capture_field_vals .= $text_field .", "; } echo $capture_field_vals; } /* returns value1, value2, value3 */ ?>
How about converting the values into JSON string, just use PHP json_encode(), you can easily decode it back to array using json_decode():
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
<?php if(isset($_POST["mytext"]) && is_array($_POST["mytext"])){ echo json_encode($_POST["mytext"]); } /* returns ["value1","value2","value3"] */ ?>

Save values into Database

Save strings on your database using MySqli.
PHP
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
<?php //Open a new connection to the MySQL server $mysqli = new mysqli('host','username','password','database_name'); //Output any connection error if ($mysqli->connect_error) { die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error); } $capture_field_vals =""; if(isset($_POST["mytext"]) && is_array($_POST["mytext"])){ $capture_field_vals = implode(",", $_POST["mytext"]); } //MySqli Insert Query $insert_row = $mysqli->query("INSERT INTO table ( captured_fields ) VALUES( $capture_field_vals )"); if($insert_row){ print 'Success! ID of last inserted record is : ' .$mysqli->insert_id .'<br />'; } ?>
  • I am trying to insert an Html form data into my DB using PHP arrays and implode function. The code works fine with no errors and gives me prompt stating values have been inserted. However, when I query into my DB the Values are not present. Html Code: User Name First Name Email submit PHP CODE : Db Created $con=mysql_connect("localhost","root","1234"); $db=mysql_select_db("abcd"); Values Passed via POST method $a=mysql_real_escape_string($_POST['uname']); $b=mysql_real_escape_string($_POST['fname']); $c=mysql_real_escape_string($_POST['email']); converting values into an array. $insertData = array('uname' => $a,'fname' => $b,'email'=>$c); Usage of implode function for inserting data in feild names in MySql. $implodedFields = implode(',', array_keys($insertData)); Usage of implode function for inserting data in field names. This will be used for inserting values in Mysql. $implodedValue =implode(',', $insertData); Finally MySql Command: $sql ="(insert into pracproj1 ($implodedFields) values ($implodedValue))"; $result = mysql_query($sql); if($result){ echo "updated"; } else "failed"; I get what I echoed after I press the submit button. But as I said. Real-time values aren't getting updated into my DB. If, somehow I don't use an array or Implode function I don't get stuck anywhere. I am trying to learn few more PHP concepts that I can use with my Html form and that's why I started working with Implode and arrays. Kindly help.
  • I have two dynamic fields. One textbox and one selectbox. I have generated the two fields dynamically using Ajax. But everytime I hit submit it only saves one row. Please help. Here's my sample insert code: <?php require 'lab/db/dbcon.php'; if(isset($_POST['btnpar'])){ $parcount = count($_POST['parid']); $parnam = array(); $parval = array(); $parnam = $_POST['parnam']; $parval = $_POST['parval']; for ($i = 0; $i <= $parcount; $i++) { $sql[] = "INSERT INTO par(parnam,parval) VALUES ('".$parnam[$i]."','".$parval[$i]."')"; echo ''; foreach ($sql as $query) { mysqli_query($con, $query); } } } ?>
  • This is something I want to do for my software, but I'm not familiar with PHP. Is there a javascript implementation of this?
  • sir, i got all my input values into a single variable, but i want to get it and store it into separate variables inorder to insert into db, based on the colum names
    • Maybe like that ; if(isset($_POST) && is_array($_POST)){ $captured =""; $a = $_POST["mytext"]; for ($i = 0; $i < count($a); $i++) { $captured = $a[$i]; //insert statement here for each $captured value; } }
    • Not possible if you are getting variables from dynamically created input fields because you don't know how many variables there will be. Either you create static fields for each column or store them as JSON or PHP serialized string.