michaelmcgurk
michaelmcgurk

Reputation: 6509

Loop data in PHP POST based on ID

I have a form (https://jsfiddle.net/jr3gnbsu/) with multiple rows/columns and I'd like to update my SQL table with this data.

HTML form snippet:

<tr class="row-id-139">
    <td class="tg-yw4l"><input type="text" name="account_dob_139" value="01/01/2001"></td>
    <td class="tg-yw4l"><input type="text" name="account_name_139" value="John Johnson"></td>
</tr>
<tr class="row-id-140">
    <td class="tg-yw4l"><input type="text" name="account_dob_140" value="01/01/2000"></td>
    <td class="tg-yw4l"><input type="text" name="account_name_140" value="Jack Thomson"></td>
</tr>

PHP script:

I have a update.php script which just has var_dump($_POST), it outputs the following:

array(4) {
  ["account_dob_139"]=> string(10) "01/01/2001"
  ["account_name_139"]=> string(12) "John Johnson"
  ["account_dob_140"]=> string(10) "01/01/2000"
  ["account_name_140"]=> string(12) "Jack Thomson"
}

Basically 139 & 140 refer to the ID so I'd love to loop through each row of the table in my PHP script and update a SQL table row.

How is this possible?

Upvotes: 1

Views: 45

Answers (1)

HTMHell
HTMHell

Reputation: 6006

Use array instead:

<tr class="row-id-139">
    <td class="tg-yw4l"><input type="text" name="account_dob[139]" value="01/01/2001"></td>
    <td class="tg-yw4l"><input type="text" name="account_name[139]" value="John Johnson"></td>
</tr>
<tr class="row-id-140">
    <td class="tg-yw4l"><input type="text" name="account_dob[140]" value="01/01/2000"></td>
    <td class="tg-yw4l"><input type="text" name="account_name[140]" value="Jack Thomson"></td>
</tr>

And in your PHP:

foreach ($_POST['account_dob'] as $id => $dob) {
    $name = $_POST['account_name'][$id];
    echo "$dob, $name";
}

Upvotes: 4

Related Questions