Search code examples
phpsqlform-processing

PhP SQL handling an 'Add More' option on a form


If I have a form that a user can optionally add extra fields, I am confused on how I should process that. For example

HTML

<input name="provider_name" type="text" />
<button class="add-more">Add Provider</button>

Javascript / jQ

var addtlCounter = 0;
$(".add-more").click(function(e){
  e.preventDefault();
  addtlCounter++;
  $(this).before('<input name="provider_name_' + addtlCounter + '" type="text" />');
})

Obviously, if there were just ONE provider_name I can just

INSERT INTO MyTable(value) VALUES ($_POST["provider_name"])

But depending on how many times the user clicks add a provider, I will get an unknown number of provider_name_*.

Any suggestions on when I go to process this form, I can tell how many additional providers they have added and INSERT accordingly.


Solution

  • Use HTML arrays.

    <input name="provider_name[]" type="text" />
    <button class="add-more">Add Provider</button>
    

    Then, in your PHP.

    foreach($_POST["provider_name"] as $provider)
    {
        echo $provider;
    }
    

    Edit:

    To have two related fields, you can have an array inside an array, but the names must be indexed. As such:

      <input name="providers[1][name]" type="text" />
      <input name="providers[1][number]" type="text" />
      <input name="providers[2][name]" type="text" />
      <input name="providers[2][number]" type="text" />
      <input name="providers[3][name]" type="text" />
      <input name="providers[3][number]" type="text" />
      <input name="providers[4][name]" type="text" />
      <input name="providers[4][number]" type="text" />
      <input name="providers[5][name]" type="text" />
      <input name="providers[5][number]" type="text" />
    

    This would result in this array:

    array(1) {
      ["providers"]=>
      array(5) {
        [1]=>
        array(2) {
          ["name"]=>
          string(0) ""
          ["number"]=>
          string(0) ""
        }
        [2]=>
        array(2) {
          ["name"]=>
          string(0) ""
          ["number"]=>
          string(0) ""
        }
        [3]=>
        array(2) {
          ["name"]=>
          string(0) ""
          ["number"]=>
          string(0) ""
        }
        [4]=>
        array(2) {
          ["name"]=>
          string(0) ""
          ["number"]=>
          string(0) ""
        }
        [5]=>
        array(2) {
          ["name"]=>
          string(0) ""
          ["number"]=>
          string(0) ""
        }
      }
    }