Jump to content

[SOLVED] Matching array form posts


djones

Recommended Posts

I have two form fields that post in an array

 

Each one of these has a check box associated with it

<input type="text" name="customer[]" value="Bob" />  <input type="checkbox" name="target[]" value="Y" /> Target
<input type="text" name="customer[]" value="John" />  <input type="checkbox" name="target[]" value="Y" /> Target
<input type="text" name="customer[]" value="Ann" />  <input type="checkbox" name="target[]" value="Y" /> Target

 

I know I can do this to get the value of one set

 

foreach($_POST['customer'] as $key => $value) {

// insert values in the DB

}

 

What's the best way for me to get both POST values matched up to enter them into the DB? I need both $_POST['customer'] and $_POST['target'] values matched up and go in the DB.

Link to comment
https://forums.phpfreaks.com/topic/99177-solved-matching-array-form-posts/
Share on other sites

You'll need to setup the keys in the form fields so they match up, eg instead of:

<input type="text" name="customer[]" value="Bob" />  <input type="checkbox" name="target[]" value="Y" /> Target
<input type="text" name="customer[]" value="John" />  <input type="checkbox" name="target[]" value="Y" /> Target
<input type="text" name="customer[]" value="Ann" />  <input type="checkbox" name="target[]" value="Y" /> Target

DO:

<input type="text" name="customer[0]" value="Bob" />  <input type="checkbox" name="target[0]" value="Y" /> Target
<input type="text" name="customer[1]" value="John" />  <input type="checkbox" name="target[1]" value="Y" /> Target
<input type="text" name="customer[2]" value="Ann" />  <input type="checkbox" name="target[2]" value="Y" /> Target

 

If you let the browser set the keys then your fields/checkboxes values will become out of sync.

 

Then in PHP do:

foreach($_POST['customer'] as $key => $value) {

    echo  'Customer: ' . $_POST['customer'][$key] . ' Checkbox: ' . (isset($_POST['target'][$key]) ? $_POST['target'][$key] : 'N') . '<br />';

}

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.