简体   繁体   English

删除按钮正在删除MySQL中最后插入的行

[英]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. id是自动编号主键int,在mysql中不为null。

If I press delete, it always deletes the last inserted row in mysql, or the newest row. 如果我按Delete键,它将始终删除mysql中最后插入的行或最新行。

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. 与其将表单标签放在while循环之外,不如将其放在里面,这样,您将拥有许多表单。

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']'";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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