Skip to content Skip to sidebar Skip to footer

How To Insert Value Of Dynamically Created Input Boxes Into Database

hello developers i am creating 2 text boxes and 1 select box dynamically using java script function... now i want to post the value of (n) fields created into database (relevant ta

Solution 1:

My favorite way to do this is to use the DOM as much as possible. Don't use counters unless you absolutely have to (they're just a source of bugs). Here's a quick example:

Html/JS/jQuery (can vary, I crafted this to make it easy to follow):

<form method="POST" id="theForm">
    <div id="fields">
        <input type="text" name="fields[]"/>
    </div>
    <input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
    $(document).ready(function() {
        $('#addField').click(function() {
            $('#fields').append(
                $('<input type="text" name="fields[]"/>')
            );
        })
    });
</script>

Note how I don't need to use any sort of counting variable. Just like PHP, you can create an array of POST variables without specifying indexes by using [] and the server (or browser? I'm not sure) will build the array for you. The order in which the <input /> fields are rendered on the page will be the order they are provided to your PHP via $_POST. This code...

foreach ($_POST['fields'] as $fieldIndex => $fieldValue) {
    doStuff($fieldValue);
}

... will process each field in the order they were added. You can even use JavaScript to re-order or remove the inputs and that will be reflected in $_POST. This method, coupled with JSON encoding, makes for a fast and easy way to handle multi-input, free-form fields.

Update:

Applying the above code to your use-case requires a small addition that may not be obvious. You'll need to create an array for each of the three inputs (stop, timing, and ampm) like so:

<form method="POST" id="theForm">
    <div id="fields">
        <input type="text" name="fields[stop][]"/>
        <input type="text" name="fields[timing][]"/>
        <select name="fields[ampm][]">
            <option value="am">AM</option>
            <option value="pm">PM</option>
        </select>
        <br/>
    </div>
    <input type="button" id="addField" value="Add Field"/>
</form>
<script type="text/javascript">
    $(document).ready(function() {
        $('#addField').click(function() {
            $('#fields').append(
                $('<input type="text" name="fields[stop][]"/>'),
                $('<input type="text" name="fields[timing][]"/>'),
                $('<select name="fields[ampm][]"><option value="am">AM</option><option value="pm">PM</option></select>'),
                $('<br/>')
            );
        })
    });
</script>

Filling out this form with some test data yields the following array:

[fields] => Array
(
    [stop] => Array
        (
            [0] => aaa
            [1] => bbb
        )

    [timing] => Array
        (
            [0] => 1111
            [1] => 2222
        )

    [ampm] => Array
        (
            [0] => am
            [1] => pm
        )

)

And to process that in PHP requires a simple old-school loop:

$numFields = count($_POST['fields']['stop']);

for ($i = 0; $i < $numFields; $i++) {

    // Pack the field up in an array for ease-of-use.
    $field = array(
        'stop' => $_POST['fields']['stop'][$i],
        'timing' => $_POST['fields']['timing'][$i],
        'ampm' => $_POST['fields']['ampm'][$i]
    );

    saveToDatabase($field);
}

Unfortunately I don't have time right now to make sure all that is correct. It should be, and if its not it may still help :). I'll check back in a few hours.


Solution 2:

name your dynamic input box "stop["+counter+"]" (using braces as part of the name) instead of adding a counter to the end of the name. Then in your post data, $_POST['stop'] will be an array of values that you can just foreach loop over with the counter as the key in the sub-array. And $_POST['stop'][1] will correspond to $_POST['timing'][1]...etc.


Solution 3:

You can construct the following HTML input fields:

<input type="text" name="data[]" />
<input type="text" name="data[]" />
<input type="text" name="data[]" />
// ...

Which will lead to an array keyed data inside $_REQUEST super global, when you var_dump($_REQUEST['data']). Try it out. You don't even need to index the data[] array, since PHP will do it for you.

You might want to process your $_REQUEST['data'] or $_POST['data'] array with a foreach loop construct:

foreach($_REQUEST['data'] as $data){
  // $data is the corresponding input field's value
}

Post a Comment for "How To Insert Value Of Dynamically Created Input Boxes Into Database"