在 MySQL 表的每一行上用 PHP 添加一个删除按钮

新手上路,请多包涵

我想在每一行上添加一个删除按钮,这样我就可以在按下按钮时删除一条记录。我是 PHP 和 MySQL 以及 Stack Overflow 的新手。

下面是我的表格,它从我的 MySQL 数据库中提取信息并且可以正常工作。

        <table class="table" >
       <tr>
       <th> Staff ID </th>
       <th> Staff Name </th>
       <th> Class </th>
       <th> Action </th>

       </tr>

       <?php

       while($book = mysqli_fetch_assoc($records)){

       echo "<tr>";
       echo "<td>".$book['Staff_ID']."</td>";
       echo "<td>".$book['Staff_Name']."</td>";
       echo "<td>".$book['Class']."</td>";
       echo "</tr>";
       }// end while loop

原文由 Hamzah Amir 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 309
2 个回答

简单地使用PHP如下(你可以使用JS)

 while($book = mysqli_fetch_assoc($records)){

echo "<tr>";
echo "<td>".$book['Staff_ID']."</td>";
echo "<td>".$book['Staff_Name']."</td>";
echo "<td>".$book['Class']."</td>";
echo "<td><a href='delete.php?id=".$book['Staff_ID']."'></a></td>"; //if you want to delete based on staff_id
echo "</tr>";
}// end while loop

在你的 delete.php 文件中,

 $id = $_GET['id'];
//Connect DB
//Create query based on the ID passed from you table
//query : delete where Staff_id = $id
// on success delete : redirect the page to original page using header() method
$dbname = "your_dbname";
$conn = mysqli_connect("localhost", "usernname", "password", $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

// sql to delete a record
$sql = "DELETE FROM Bookings WHERE Staff_ID = $id";

if (mysqli_query($conn, $sql)) {
    mysqli_close($conn);
    header('Location: book.php'); //If book.php is your main page where you list your all records
    exit;
} else {
    echo "Error deleting record";
}

原文由 BetaDev 发布,翻译遵循 CC BY-SA 3.0 许可协议

创建一个接收 $_GET[‘id’] 的 delete.php 文件,然后在他们转到该页面时运行 sql 以删除该记录。通过两种方式完成:如下所示的锚标记,

或者制作一个按钮而不是锚运行 ajax(通过 jquery)发送该 id 并运行我上面提到的 delete.php 脚本。

 table class="table" >
       <tr>
       <th> Staff ID </th>
       <th> Staff Name </th>
       <th> Class </th>
       <th> Action </th>

       </tr>

       <?php

       while($book = mysqli_fetch_assoc($records)){

       echo "<tr>";
       echo "<td>".$book['Staff_ID']."</td>";
       echo "<td>".$book['Staff_Name']."</td>";
       echo "<td>".$book['Class']."</td>";
       echo "<td><a href='delete.php?id=".$book['Staff_ID']."'>Delete</a></td>";
       echo "</tr>";
       }// end while loop

原文由 clearshot66 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题