Josh Curren
Josh Curren

Reputation: 10226

Gathering POST data from similar fields

I am posting a form that has many similar fields (artist1, artist2, .... artist20). I am trying to add them to a database but I am not sure how to easily get all of the posted data with out having to write out each one separately. How can I combine an int to a string so that I dont have to write each one out? This is one way I tried that didnt work:

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

I also tried (which didnt work):

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

Upvotes: 1

Views: 160

Answers (1)

nickf
nickf

Reputation: 546025

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 that, this is what you'll get in PHP:

print_r($_POST);

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

...as for getting them into a database, see this question: insert two kinds of array in the same table

Upvotes: 5

Related Questions