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.

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.

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:

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.

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():

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.

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 />';
}
?>

36 Comments Add Comment

  • 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

     Reply
    • 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.

    • 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;

      }

      }

  • $insert_row = $mysqli->query(“INSERT INTO users ( captured_fields ) VALUES( $capture_field_vals )”); What are the captured_fields ?

     Reply
  • I am creating tr from javascript. I am concating name=’list’+cnt+’ to form list array.
    I ahve plus and minus button to add or delete table row.
    Now if i am getting array like as below –

    [list_1] => Array
    (
    [0] => val1
    [1] => val2
    [2] => val3
    )

    [list_2] => Array
    (
    [0] => val1
    [1] => val2
    [2] => val3
    [3] => val4
    )

    [list_6] => Array
    (
    [0] =>val1
    [1] => val2
    )

    then how to iterate through these dynamic array.

    Thanks in advance

     Reply
  • hi, if i dunt want to use implode(“,”, $_POST[“mytext”]) save to database what can i use for this?

     Reply
  • Man, that was realy helpful, thanks a lot for the help and the examples so well explained.

     Reply
  • Thanks a lot…

     Reply
  • how can i update these fields values in database like for example if once a user fill the three fields and submit the data and when the user want to edit this information and He added an another extra field then how can i add that extra and update earlier fields data together ………please help me

     Reply
    • I think I’m having the same issue as you and especially Ryan. I have a list of dynamic input fields like what we say created in the previous tutorial. But when I save the form after adding a couple fields, I only have the first one saved. In my testing I just added three static input fields to the page from the beginning and it works fine. So my issue is not with the loop over my input fields, but the creation of dynamic fields. I and using WordPress Boilerplate so my code might be different, but here is a snippet of what I have.

      Loading saved data to the form.

      $locations = get_option($this->plugin_name .”_location”);

      foreach($locations as $key=>$item){
      echo ‘

      Location Title
      plugin_name.’_location[]” value=”‘.$item.'” />

      Remove
      ‘;
      }

      Then in my function to register_setting

      $locations = array();

      if(isset($input) && is_array($input)){
      foreach($input as $key => $text_field){
      $locations[$text_field] = sanitize_text_field($text_field);
      }
      }

      My Javascript works fine so I’m not going to show that.

      The main issue here is PHP not seeing the created fieldsets and inputs when submit is pressed.

  • how about input type file? pls contanct me if you dont mind, thanks

     Reply
  • If I want alert when the second row textbox value same as first row textbox value, how I can do it??

     Reply
  • Thanks a lot !! You saved my day

     Reply
  • Hi,
    I have a form that has two dynamic fields and i have used the post array

    $business_director=””;
    if(isset($_POST[“director”],$_POST[“need”])){
    foreach($_POST[“director”] as $key => $text_field){
    $business_director.= $text_field .”, “;
    }

    but only the first field information is displayed in the database but with the comma.Like lets say i entered my name ‘Ryan Munene’ in the first field then i enter another in the dynamic field it will appear :

    Ryan Munene,
    in the names column in the db.

    I think I’m missing sth but i cant figure out what,any help will be much appreciated

     Reply
    • 1
      2
      3
      4
      5
      6
      $business_director;
      if(isset($_POST["director"]) && isset($_POST["need"])){
          foreach($_POST[“director”] as $key => $text_field){
              $business_director .= $text_field .”, “;
          }
      }
  • Hi, You example is great, How do i get value of each field in javascript or jquery?

     Reply
  • this is more help me, thanks

     Reply
  • How to use foreach if you are having two arrays

    example,
    i want to get the value from $_POST[“mytext1”] and $_POST[“mytext2”]

     Reply
    • $_POST is 1 array not 2, mytext1 and mytext2 are 2 indexes of $_POST

      1
      2
      3
      4
      5
      6
      7
      8
      // iterate / loop through post,
      // store the index in key and the contents of each index in value
      foreach($_POST as $key =&gt; $value){
          // compare each index or "key" to the string mytext1 or mytext2
          if ($key == "mytext1" || $key == "mytext2" ){
              // now place your code here to do something with $value
          }
      }
  • Thanks for sharing!

     Reply
  • This Help me alot. Thanks u alot

     Reply
  • Can I Generate X Number of Input Feilds Using php with Different Values Comming from Database?

     Reply
  • Using Implode Function of PHP i have stored dynamic textbox values into MySQL.

    Now how can i retrieve the same values into textbox again so user can edit or update it.

     Reply
  • why is it inserting in one row i want it in 2 rows

     Reply
  • Maybe better serialize content before saving values?)

     Reply
  • Thank you for sharing! Your post was very useful for me.

     Reply
  • Add More Fields

    collect_vals.php
    print_r($_POST[“mytext”]);

    Result- shows me only first input box value.
    can anyone tell me whats the problem

     Reply
    • Might be array problem. Convert [] to be [0] [1] [2] …. [10].

      $(document).ready(function() {
      var max_fields = 10; //maximum input boxes allowed
      var wrapper = $(“.input_fields_wrap”); //Fields wrapper
      var add_button = $(“.add_field_button”); //Add button ID

      var x = 0; //initlal text box count – Array start from 0
      $(add_button).click(function(e){ //on add input button click
      e.preventDefault();
      if(x < max_fields){ //max input box allowed
      x++; //text box increment
      $(wrapper).append('Remove‘); //add input box
      }
      });

      $(wrapper).on(“click”,”.remove_field”, function(e){ //user click on remove text
      e.preventDefault(); $(this).parent(‘div’).remove(); x–;
      })
      });

    • input type=”text” name=”mytext[‘+ x +’]”

  • Sir, what if i have two different dynamic fields like and
    and i have a column where i want to insert either one or the two how do i go about it please

     Reply
  • This post (and obviously the previus) is what exactly I was looking for to create a configurable product catalogue. Thanks for sharing!

     Reply