2

I have an input field iterated 3 times and I would like to store the values entered in each of the fields in a PHP array.

I called each OPTION item[] hoping that it would save each value in a same array.

Would this work? If yes, how would I retrieve it on PHP?

Here is my form:

<tr>
    <td>Items</td>
    <td><select><?php
    $items = $con -> prepare("SELECT * FROM item_descr");
    $items ->execute();
    while($info = $items->fetch(PDO::FETCH_ASSOC)) {
    ?>
    <option name="item[]" value="<?=$info['id_item']?>"><?=$info['name']?></option><?php } ?>
    </td>
    <td>Quantity:</td>
    <td><input name="quantity[]"></td>
        <td><a href="" id="addItem">ADD</a></td>
    </tr>
    <tr class="moreItems">
    <td>Items</td>
    <td><select><?php
    while($info = $items->fetch(PDO::FETCH_ASSOC)) {
    ?>
    <option name="item[]" value="<?=$info['id_item']?>"><?=$info['name']?></option><?php } ?>
    </td>
    <td>Quantity:</td>
    <td><input name="quantity[]"></td>
</tr>
<tr class="moreItems">
    <td>Items</td>
    <td><select><?php
    while($info = $items->fetch(PDO::FETCH_ASSOC)) {
    ?>
    <option name="item[]" value="<?=$info['id_item']?>"><?=$info['name']?></option><?php } ?>
    </td>
    <td>Quantity:</td>
    <td><input name="quantity[]"></td>
</tr>
3
  • 3
    You need to set the name attribute on the select tag, not the option tag Commented Jun 4, 2013 at 16:29
  • Thx, that would work for the SELECT. How about for the INPUT field? Commented Jun 4, 2013 at 16:33
  • 1
    works the same.. name="something[]" after post to php would be $_POST['something'][0] = 'sample', $_POST['something'][1] = 'sample' Commented Jun 4, 2013 at 16:34

1 Answer 1

3

Change the [] from the option tag to your select tag:

<tr>
    <td>Items</td>
    <td><select name="items[]">
    <?php
        $items = $con -> prepare("SELECT * FROM item_descr");
        $items ->execute();

        while($info = $items->fetch(PDO::FETCH_ASSOC)) {
    ?>
    <option name="item" value="<?=$info['id_item']?>"><?=$info['name']?></option>
    <?php } ?>
    </td>
    <td>Quantity:</td>
    <td><input name="quantity[]"></td>
    <td><a href="" id="addItem">ADD</a></td>
</tr>

Then on your PHP page, to retrieve the values:

foreach($_POST['items'] as $key => $itemValue)
{
    echo 'Item: ' . $itemValue . '<br />';
    echo 'Quantity: ' . $_POST['quantity'][$key] . '<br /><br />';
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.