Collecting POST data from similar fields

I am submitting a form that has many similar fields (artist1, artist2, .... artist20). I'm trying to add them to the database, but I'm not sure how easy it is to get all the posted data without having to write it down separately. How can I concatenate the int into a string so that I don't have to write each one? This is one of the ways I didn't work with:

for( $i=0; $i <= 20; $i++ )
{
   $artist = $_POST['artist'.$i] 
}

      

I've also tried (which doesn't work):

for( $i=0; $i <= 20; $i++ )
{
   $art = 'artist' . $i;
   $artist = $_POST[ $art ];
}

      

+1


a source to share


1 answer


You can name your HTML elements with square brackets and PHP will convert them to an array for you:

<input type="text" name="artist[]" value="abc" />
<input type="text" name="artist[]" value="def" />
<input type="text" name="artist[]" value="ghi" />
<input type="text" name="artist[]" value="jkl" />

      

when you post this, this is what you get in PHP:



print_r($_POST);

/* array(
    artist => array(
        0 => "abc",
        1 => "def",
        2 => "ghi",
        3 => "jkl"
    )
) */

      

... how to get them into the database, see this question: insert two kinds of array into the same table

+5


a source







All Articles