简体   繁体   中英

delete button is deleting the last inserted row in Mysql

<?php
if(isset($_POST['delete_dayOff'])) {
 $DeleteQuery = "DELETE FROM dayoff WHERE id = '$_POST[hidden]'";
 mysqli_query($db,$DeleteQuery);
 };

// display records

$select_employee = "SELECT * FROM dayoff";
$result = $db->query($select_employee);
 ?>
<table>
<div id="Day-off Employees">
<?php
     echo "<table><caption>Day-off Employees</caption><tr>
    <th>Employee First Name</th>
    <th>Employee Last Name</th>
    <th>Day-Off</th>

    </tr>";

    echo "<form action=dayoff.php method=post>";

     // output data of each row
     while($row = $result->fetch_assoc()) {

         echo "<tr>";

         echo "<td>" . $row["employeefname"]. "</td>";
         echo "<td>" . $row["employeelname"]. "</td>";
         echo "<td>" . $row["date"]. "</td>";


echo "<td>" . "<input type=hidden name=hidden  value=" . $row["id"].  " </td>";
echo "<td>" . "<input  type=submit   name=delete_dayOff value=delete  >" . " </td>";
echo "</tr>";
}

echo "</form";


echo "</table>";


?>

I'm using the same exact script on another page and it's working perfectly. id is autonumber primary key int, not null in mysql.

If I press delete, it always deletes the last inserted row in mysql, or the newest row.

If i echo the content of hidden button, it is correct, but if i press the delete button, it deletes the wrong row, why?

It's because you have one and only form although you want to be able to delete a single row. You should have as many form that you have rows.

Instead of putting your form tags outside your while loop, you should put them inside, this way, you'll have many forms.

The trouble with having only one form is that you named the hidden field with the same name so it will take the last one.

do

while($row = $result->fetch_assoc()) {
    echo "<tr>";
     ...
    echo '<td><form ...><input hidden...><input type="submit"...></form></td>';
    ...
}

$_POST[hidden]应该是$_POST['hidden'] ;

 $DeleteQuery = "DELETE FROM dayoff WHERE id = '$_POST['hidden']'";

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