Skip to content
Advertisement

How to delete specified row in a database table using post method in php

//Deleting is working. However, I can’t delete the specified row in the table. It always deletes the last row. I hope you could help me. Thank you! This is my code for displaying data from database:

<form action="deleteCart.php" method = "post" role="form">
 <?php 
   while ($row = mysqli_fetch_array($result2)) { 
  ?>
    <tr style="text-align: center;">
     <td> <img src="images/<?php echo $row["ImageProduct1"]; ?>"/>  
     <td><?php echo $row['NameProduct1']; ?> </td>
     <td>#<?php echo $row['OrderID']; ?></td>
     <td><?php echo $row['OrderQuantity']; ?></td>
     <td><input type="submit" name="cancelOrder" value = "Cancel" ></td>
     <td><input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>"></td>
    </tr>
 <?php 
    } 
 ?>  
</form>

//This is my code for deleting:

if(isset($_POST['cancelOrder'])){
    orderID = $_POST['hiddenID'];
    mysqli_query($con, "DELETE FROM OrderTable WHERE OrderID=$_POST[hiddenID];");
    header('location: deleteCart.php'); 
}

Advertisement

Answer

Delete only the last record because you submitting form whole table record. you should try this code. it will work fine.

this will submit separate record.

 <?php 
   while ($row = mysqli_fetch_array($result2)) { 
  ?>
    <form action="deleteCart.php" method = "post" role="form"> 
       <tr style="text-align: center;">
           <td><img src="images/<?php echo $row["ImageProduct1"]; ?>"/>  
           <td><?php echo $row['NameProduct1']; ?> </td>
           <td>#<?php echo $row['OrderID']; ?></td>
           <td><?php echo $row['OrderQuantity']; ?></td>
           <td>
              <input type="hidden" name="hiddenID" value="<?php echo $row['OrderID']; ?>">
              <input type="submit" name="cancelOrder" value = "Cancel" >
           </td>
     


       </tr>
   </form>
 <?php 
    } 
 ?>  

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement