samyb8
samyb8

Reputation: 2588

Storing inputs from multiple SELECT tags into a PHP array

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>

Upvotes: 2

Views: 5664

Answers (1)

Phil Cross
Phil Cross

Reputation: 9302

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

Upvotes: 3

Related Questions