$_POST to receive dynamic amount of fields to update

arrays, php, sql

Solution

have you ever tried something like:

<input name="header[]" />
<input name="header[]" />
<input name="header[]" />

This will create a multi-dimensional array on the PHP side which you can easily cycle through.

echo $_POST['header'][0];
echo $_POST['header'][1];
echo $_POST['header'][2];

It would also be faster to use prepared statements for this, although you would have to switch to using something like PDO for your database interactions. Here's an example of looping thorugh using the code you showed above.

$fieldCount = count($_POST['header']);
for ($i = 0; $i < $fieldCount; $i++) {
   $sql = 'UPDATE about SET about_header = \''.$_POST['header'][$i].'\', about_content = \''.$_POST['post'][$i].'\' WHERE about_id = \''.$_POST['id'][$i].'\'';
   mysql_query($sql);
}

Problem

I wasn't sure what to title this question. Here's my goal: On page one, I have a form that is generated from the database. It loops through assigning a counting variable to the id of the fields (ie: header_1, header_2, header_3...) Now, the amount of fields may vary as I need the ability to add extra information (ie: header_4, header_5). When I submit my form, how can I create a variable for each field? `$header1 = $_POST['header_1']` Essentially, I am looking for an array-based (or variable variable-based) way of simplifying something like this: ``` $sql="UPDATE about SET about_header = '$head1', about_content = '$post1' WHERE about_id = '$id1'"; $result = mysql_query($sql); $sql="UPDATE about SET about_header = '$head2', about_content = '$post2' WHERE about_id = '$id2'"; $result = mysql_query($sql); $sql="UPDATE about SET about_header = '$head3', about_content = '$post3' WHERE about_id = '$id3'"; $result = mysql_query($sql); ``` I imagine a query like this would work but I'm not sure how to handle the array of information that I would need help building as well. ``` $y=1; $sql="UPDATE about SET about_header = '$head$y', about_content = '$post$y' WHERE about_id = '$id$y'"; ``` I hope I explained this well enough. Any help would be great. Thanks!

Original source