user3191346
user3191346

Reputation: 9

PHP - Forms only using last row in form

I have a table that generates a number of rows according to how many rows are in the database, but the submit button is only taking the last row in the table and not the one I selected. Any ideas of what I am doing wrong?

<?php
                $result = mysql_query("SELECT * FROM booking");

                while($row = mysql_fetch_array($result))
                {

                ?>

<form class='table-form' id='form' method='post'>

                    <tr>

                    <input id="bookid" type="hidden" name="bookid" value="<?php echo ($row['booking_id']); ?>" />

                    <td>

                    <input id="bookingid"<?php echo ($row['booking_id']);?>

                    </td>
                    <td>
                        <?php echo ($row['user_id']); ?>
                    </td>
                    <td>
                        <?php echo ($row['event_id']); ?>
                    </td>
                    <td>
                        <?php echo ($row['payment_type']); ?>
                    </td>
                    <td>
                        <?php echo ($row['booking_date']); ?>
                    </td>
                    <td>
                        <button id="cancel" name="cancel" type="submit">Cancel</button>
                    </td>
                </tr>




                <?php
                }
                ?>


                </form>

            </table>
        </div>

        <?php

                if (isset($_POST['bookid'])){

                $bookid = ($_POST['bookid']);

                $result = mysql_query("DELETE FROM booking
                WHERE booking_id = '$bookid'");
                }
?>

Upvotes: 0

Views: 217

Answers (2)

Aris
Aris

Reputation: 5057

When you have multiple elements with the 'same name' you need to have their names defined in an array like this:

 <input type="hidden" name="bookid[]" value="<?php echo ($row['booking_id']); ?>" />

When you process the form you can read them like this, and treat them like an array:

$bookids = $_POST['bookid'];

foreach($bookids as $eachBookId)
{ do some processing ... }

Upvotes: 0

Quentin
Quentin

Reputation: 943645

All your inputs have the same name and that name does not end in the characters []. PHP will therefore only accept the last value.

Rename them to include [] at the end of the name if you want them to all be available.

Additionally, you are generating invalid HTML. Browsers may move elements placed in invalid parts of tables so they are outside the table when they try to recover from this type of error. This could cause you more problems. Use a validator to identify the errors, and fix them.

Upvotes: 1

Related Questions