How To Capture Array Values from Dynamic input Fields Using PHP?

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.
<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[] of each 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 another value to 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 array's indexed number, but this will cause error if indexed value doesn't exist in array.
echo $_POST["mytext"][0];
echo $_POST["mytext"][1];
Another way is using PHP implode, it converts POST array into string, separated by commas. Just make sure POST variable is not empty:
if($_POST){
    $subject = implode(",", $_POST["mytext"]);
    echo $text;
}
You can also loop through each POST array like so, result is same as above.
<?php
if(isset($_POST["mytext"])){
    
    $capture_field_vals ="";
    foreach($_POST["mytext"] as $key => $text_field){
        $capture_field_vals .= $text_field .", ";
    }
    
    echo $capture_field_vals;
}
?>

Save values into Database
You can save above captured strings on your database using MySql/MySqli.
<?php

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


Source: Source: Capture Array Values from Dynamic input Fields using PHP

Comments

  1. Like your previous post, we are able to add multiple dynamic fields using jQuery. In this

    Web Tutorial
    we have collected several values from those dynamically generated input fields, which can be displayed on user browser or store in MySql database

    ReplyDelete

Post a Comment

Popular Posts