Jump to content

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 />';

}

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.