php html删除按钮删除MySQL行

时间:2017-05-14 21:24:13

标签: php html mysql

我正在尝试删除页面上显示的MySQL行。是的,我想从数据库中删除该条目。

我已经尝试了在这些表单和其他谷歌相关搜索中提到的几个解决方案,以了解我要完成的任务。

这是我目前的代码:

<?php
//  Display information from table & add remove button
$servername = "";
$username = "website";
$password = "";
$dbname = "website";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT location, thelink, status FROM main_page";
$result = $conn->query($sql);


if ($result->num_rows > 0) {
    echo "<table align=\"center\"><tr><th align=\"center\">Image</th><th align=\"center\">Information</th></tr><br />";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr><td><img src=".$row["location"]. "><br /></td><td align=\"center\"><br /> ".$row["status"]. "<br /><br /><a href=\"delete.php\">Delete</a></td></tr>";


    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>

当我尝试将$ row变量添加到delete.php行的末尾时,它不会显示,或者由于错误而无法加载页面。

2 个答案:

答案 0 :(得分:0)

在链接处

<a href="delete.php?id=<?php echo row['id']; ?>">Delete</a>

现在在delete.php上执行

<?php
if(isset($_GET["id"])){
$id=$_GET["id"];
// HERE YOU CAN MAKE QUERY TO DELETE THE RECORD
}
 ?>

答案 1 :(得分:0)

您需要将每行的ID传递到链接中以删除自身:

if ($result->num_rows > 0) {
    echo "<table align=\"center\"><tr><th align=\"center\">Image</th><th align=\"center\">Information</th></tr><br />";
    while($row = $result->fetch_assoc()) {
        echo "<tr><td><img src=".$row["location"]. "><br /></td><td align=\"center\"><br /> ".$row["status"]. "<br /><br /><a href=\"delete.php?id=" . $row["id"] . "\">Delete</a></td></tr>";
    }
    echo "</table>";
}

然后在delete.php上,您需要根据id $ _GET参数检查ID:

// Connection needs to be defined again -- ideally from an include()
$conn = new mysqli($servername, $username, $password, $dbname);

if(isset($_GET["id"])){
  $stmt = $conn->prepare("DELETE FROM table WHERE ID = ?");
  $stmt->bind_param('i', $_GET["id"]));
  $stmt->execute(); 
  $stmt->close();
}

请记住,通过$ _GET请求进行删除是非常危险的,因为有人可以通过浏览器访问delete.php?id=1并删除给定记录;您可能希望将$ _POST合并到删除中。

希望这有帮助! :)