-1

I have an inventory program I am working on and am wondering how to determine which button was clicked. The user sees a list of each item in their inventory, and next to each item there is a delete button. I am trying to figure out how to delete the specific item when the remove button next to it is clicked.

Here is the code that displays the inventory:

while ($row = mysqli_fetch_array($result)){
    echo "<tr><td width='500px'>".$row['Name']."</td>";
    echo "<td width='200px'><center><input type='Submit' value='Remove' name='".$row['Name']."'></center></td></tr>";
}

Here is what I have so far to remove the item:

if (isset($_POST['Submit'])) {
     $Name = $_POST['name'];
     $sql = "DELETE * FROM database WHERE Name = '$Name'";

     if ($conn->query($sql) === TRUE) {
          $message = "Successfully Removed " . $Name;
          echo "<center><span style='color: red; font-size: 20px'><b>$message</b></span></center>";
     } else {
          echo "Error: " . $sql . "<br>" . $conn->error;
     }
     mysqli_close($conn); //connection close

 }
Android198
  • 35
  • 4
Abby S
  • 1
  • 2
  • Watch out! Your code is vulnerable to SQL injection. For more information check [What is SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work) and [How to prevent](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) – Mathias Jun 29 '19 at 06:17

1 Answers1

1

First change name and value of your button.

while ($row = mysqli_fetch_array($result)){
    echo "<tr><td width='500px'>".$row['Name']."</td>";
    echo "<td width='200px'><center><input type='Submit' value='".$row['Name']."' name='name'></center></td></tr>";
}

Then check for name index in $_POST array and not Submit because input fields' name attribute becomes the index of $_POST array.

if (isset($_POST['name'])) {
     $Name = $_POST['name'];
     $sql = "DELETE * FROM database WHERE Name = '$Name'";

     if ($conn->query($sql) === TRUE) {
          $message = "Successfully Removed " . $Name;
          echo "<center><span style='color: red; font-size: 20px'><b>$message</b></span></center>";
     } else {
          echo "Error: " . $sql . "<br>" . $conn->error;
     }
     mysqli_close($conn); //connection close

 }
Atal Prateek
  • 541
  • 3
  • 7