Skip to content
Advertisement

How can I delete 1 row from a table using a submit button?

I am using a foreach loop to display my data. Im getting data from a table with reservations, which the customer is able to delete.

This is my current code:

if(isset($_POST['verwijder']))
{
$resid= $pers->reserveringnummer;

$query = "DELETE FROM reservering WHERE reserveringnummer = :resid;";
$stm = $con->prepare($query);
$stm->bindParam(':resid', $resid, PDO::PARAM_STR, 20);
if($stm->execute() == true)
{
    ?>
    <script type="text/javascript">
    window.location.href = 'greservering.php';
    </script>
    <?php
}   else {
echo ("Mislukt");
}
}

//pers->reserveringnummer = reservation id loaded from database

This code selects the id of the row the button is in, and deletes the row with this id. It all worked with 1 row, but when I tried it with 2 rows, it deleted both.

All of this happens inside of a foreach loop, so every row has a submit button with the same name (verwijder).

When I click a submit button, all of the buttons execute the action, and delete themselves.

Is there anyway to solve this issue?

EDIT:

Form code: (just a button per row)

//query to get all reservations
foreach ($result as $pers) {
?>
    //some row data
    <form method="post">
    <input type="submit" class="dropdown-item text-danger" name="verwijder" value="Verwijder">
    </form>
<?php
//delete code using submit
}

Advertisement

Answer

It looks like you aren’t passing any information on which reservation should be deleted. How does $pers->reserveringnummer; load the number and know which of the buttons was pressed?

In the delete form where you display the reservations you would probably need to pass the number in a hidden input field like this

<input type="hidden" name="resid" value="<?= $resid ?>" />

and then in your delete code you use this id to delete the reservation.

Advertisement