0

//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'); 
}
nit21
  • 125
  • 1
  • 4
  • 13
  • Can you show a print_r($_POST); – zyad osseyran Oct 02 '20 at 09:16
  • @zyadosseyran it's not showing in the website – nit21 Oct 02 '20 at 09:26
  • **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Oct 02 '20 at 11:26
  • okayy thanks for that, but I'm still new to php.. how am I gonna put this in prepared statements?@Dharman – nit21 Oct 03 '20 at 12:43

1 Answers1

0

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 
    } 
 ?>  

Kashif Shahzad
  • 135
  • 1
  • 6