简体   繁体   中英

PHP delete button on HTML table

I have outputted the results from a MySQL table to an HTML table. In the last column, I want a delete function to work for the specific row but my code doesn't seem to work.

I have now adjusted my code due to the comments you kind people have left me and it is now recognizing the row it needs to delete but will not delete it? I am properly stumped with this one!

Again if anybody can explain this to me and provide code examples to correct this then thank you.

This is my code for the page:

<table border="1" cellpadding="1" cellspacing="1">

<tr>
    <th>AdoptionID</th>
    <th>UserID</th>
    <th>AnimalID</th>
    <th>Cancel</th>
<tr>

<?php
include("PHP/Connection.php");

$sql=mysql_query("SELECT * FROM `adoptionrequest` WHERE `userID` = '1' AND `approved` = 'Awaiting Approval' ");

while($requests=mysql_fetch_assoc($sql)){

    echo"<tr>";

    echo "<td>".$requests['adoptionID']."</td>";
    echo "<td>".$requests['userID']."</td>";
    echo "<td>".$requests['animalID']."</td>";
    ?>
    <td>
        <form action='PHP/Delete.php?id=<?php echo $requests['adoptionID'];?>' method="post">
        <input type="hidden" name="adoptionID" value="<?php echo $requests['adoptionID']; ?>">
        <input type="submit" value="Cancel" name="submit"></form>
    </td>

    <?php
    echo"<tr>";
}

?>

</table>

and for the Delete.php:

<?php 
$id = $_GET['id'];
  $query = "DELETE FROM contacts WHERE adoptionID=$id LIMIT 1";
?>

Change the field name in the HTML form

<form action='PHP/delete.php' method="post">
    <input type="hidden" name="adoptionID" value="<?php echo $requests['adoptionID']; ?>">
    <input type="submit" value="Cancel" name="submit">
</form>

Modfity delete.php

<?php
// Casting it to an int protects against SQL injection
$adoptionID = (int)$_POST['adoptionID'];

//Define the query
$query = "DELETE FROM contacts WHERE adoptionID={$adoptionID} LIMIT 1";

//sends the query to delete the entry
mysql_query($query); // <- You should be using mysqli_query
$query = "DELETE FROM contacts WHERE adoptionID={$_POST['adoptionID']} LIMIT 1";

has invalid post data. try

  $x = mysql_real_escape_string($_GET['adoptionID']);
  $query = "DELETE FROM contacts WHERE adoptionID=$x LIMIT 1";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM