首页 > 解决方案 > DELETE ROW where ID = $id 不删除请求的行

问题描述

我正在尝试实现一项功能,该功能允许我从学生列表中删除学生。(这是一张桌子)

虽然当我单击删除时,它不会删除当前行中的学生但是......如果我将查询更改为 DELETE FROM students WHERE id = 1 ......它可以工作。所以,我相信问题在于无法从当前行中获取 id,但是,我不确定我哪里出了问题。

//学生名单.php

<?php include ('../resources/styling.html'); ?>
<?php include ('adminNavbar.php'); ?>

<!--HTML styling of the table that outputs the database entries, bootstrap styling-->

<div class="container content-area">
<div class="row">
<div class="col-md-12">
<div class="panel">
<br>

<div class="text-center border border-light p-5">
<p class="h4 mb-4">All Student Accounts</p>
</div>
<br>

<table class="table table-hover">
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">First Name</th>
      <th scope="col">Surname</th>
      <th scope="col">Programme</th>
      <th scope="col">Student ID</th>
      <th scope="col">Delete</th>
    </tr>

  </thead>
  <tbody>
  </div>
  </div>
  </div>
  </div>

<?php
include ('../resources/config.php');

$sql = "SELECT id,firstname, surname, programme, studentid FROM students";
$result = $db->query($sql);

// while loop to output data of each row for each student in database

while($row = $result->fetch_assoc()) {

    echo '<tr>
    <td scope="row">' . $row["id"]. '</td>
                  <td>' . $row["firstname"] .'</td>
                  <td> '.$row["surname"] .'</td>
                  <td> '.$row["programme"] .'</td>
                  <td> '.$row["studentid"] .'</td>
                  <td ><a class="btn btn-danger"   href="MLdelete.php?id=".$row["id"].""</a> Delete</td>
    </tr>';

}
$db->close();
?>

</tbody>
</table>

<div class="text-center border border-light p-5">
<a href="createStudent.php" class="btn btn-primary">Add New Student Account</a>
</div>

//MLdelete.php

<?php
require ( '../resources/config.php' );

if(isset($_GET["id"])){

    $id = mysqli_real_escape_string($db, $_GET["id"]);
    // sql to delete a record
    $query = "DELETE FROM students WHERE id ='{$id}'";

    $del=mysqli_query($db,$query);

    if ($del) {
       header("Location: StudentsList.php");
    } else {
        echo "Error deleting record: " . $db->error;
    }
}
    $db->close();

?>

基本上,当我单击一行的删除按钮时,什么也没有发生。

标签: phpsql

解决方案


您没有正确引用您的<a>链接。

它应该是

<td ><a class="btn btn-danger"   href="MLdelete.php?id=' . $row["id"] . '"</a> Delete</td>

还可以根据我的评论使用准备好的语句。这将防止 SQL 注入攻击。

通过PHP 手册查看准备好的语句解释和示例


推荐阅读