Multiple inputs with same name through POST in php

后端 未结 5 2128
误落风尘
误落风尘 2020-11-22 02:54

Is it possible to get multiple inputs of the same name to post and then access them from PHP? The idea is this: I have a form that allows the entry of an indefinite number

相关标签:
5条回答
  • 2020-11-22 03:02

    In your html you can pass in an array for the name i.e

    <input type="text" name="address[]" /> 
    

    This way php will receive an array of addresses.

    0 讨论(0)
  • 2020-11-22 03:05

    Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

    <h1>First Address</h1>
    <input name="street[]" value="Hauptstr" />
    <input name="city[]" value="Berlin"  />
    
    <h2>Second Address</h2>
    <input name="street[]" value="Wallstreet" />
    <input name="city[]" value="New York" />
    

    The outcome would be

    $POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
              'city' => [ 'Berlin' , 'New York'] ];
    

    To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

    <h1>First Address</h1>
    <input name="address[1][street]" value="Hauptstr" />
    <input name="address[1][city]" value="Berlin"  />
    
    <h2>Second Address</h2>
    <input name="address[2][street]" value="Wallstreet" />
    <input name="address[2][city]" value="New York" />
    

    The outcome would be

    $POST = [ 'address' => [ 
                     1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                     2 => ['street' => 'Wallstreet', 'city' => 'New York'],
                  ]
            ]
    
    0 讨论(0)
  • 2020-11-22 03:06

    It can be:

    echo "Welcome".$_POST['firstname'].$_POST['lastname'];
    
    0 讨论(0)
  • 2020-11-22 03:10

    For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.

    The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval] (string or int) which then allows you to refer to an existing record.

    0 讨论(0)
  • 2020-11-22 03:13

    Change the names of your inputs:

    <input name="xyz[]" value="Lorem" />
    <input name="xyz[]" value="ipsum"  />
    <input name="xyz[]" value="dolor" />
    <input name="xyz[]" value="sit" />
    <input name="xyz[]" value="amet" />
    

    Then:

    $_POST['xyz'][0] == 'Lorem'
    $_POST['xyz'][4] == 'amet'
    

    If so, that would make my life ten times easier, as I could send an indefinite amount of information through a form and get it processed by the server simply by looping through the array of items with the name "xyz".

    Note that this is probably the wrong solution. Obviously, it depends on the data you are sending.

    0 讨论(0)
提交回复
热议问题