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
12345678910
<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
12
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
12345678
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
12345678910111213
<?php
if(isset($_POST["mytext"]) &#038;&#038; 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
123456789
<?php
if(isset($_POST["mytext"]) &#038;&#038; 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
123456789101112131415161718192021
<?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 />';
}
?>
  • 53 Comments

    Add Comment
    • Suen
      I can not know php array for multi name data Enter Name 1 Enter Name 2 Enter Name 3 Enter Name 1 Enter Name 2 Enter Name 3 Enter Name 1 Enter Name 2 Enter Name 3 Enter Name 1 Enter Name 2 Enter Name 3 Enter Name 1 Enter Name 2 Enter Name 3 ########### Please tell me how to change below php code ###########
      12345678
      &lt;?php
      //Remove the spaces in PHP opening tag
      $variable = $_POST[&#039;txtname&#039;];
      
      foreach( $variable as $n ) {
        print &quot;The name is &quot;.$n .&quot;";
      }
      ?&gt;
    • Tahir
      I have html table and in 1 td i have a name and other td is a button called update. now i want to update the name according to button.
    • Aditya
      /MySqli Update Query $update_row = $mysqli->query("update table set captured_field = $capture_field_vals where captured_field_id=$capture_field_id_vals"); if($update_row){ print 'Success! ID of last updated record is : ' .$mysqli->updated_id .''; } What is capture_field_id_vals ???
    • Dikshant Ghimire
      What to do if you have 2 diffeent input fields?
    • Fazal
      how to get while loop imposed input values in if(isset($_POST['submit'])) and then assign them to dynamic variable in php
    • Narayan
      How to update..?
      • Venkaramana Narayan
        123456
        //MySqli Update Query
        $update_row = $mysqli-&gt;query("update table set captured_field = $capture_field_vals where captured_field_id=$capture_field_id_vals");
        
        if($update_row){
            print 'Success! ID of last updated record is : ' .$mysqli-&gt;updated_id .'';
        }
    • Suriya
      Hi, Thank you So much. helped me a lot. thank you
    • Ajay
      Hi, In the form that you created in PHP, how can I capture the value of these fields created dynamically in JQuery? Thanks !
    • Koushik
      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.
      • Sunny Koushik
        you should create your table names directly from database then just call it to your code wisely. use serialize() function to convert it to encoded form which is must for storing data in database .