我有一个通过PHP / MySQL输出的项目列表。我还在一列中有一个“编辑”按钮和一个“删除”按钮。我试图找出如何通过单击删除按钮删除特定行上的列表项。我尝试过以下方法:
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
} else {
echo "Cannot delete";
}
}
这当然不起作用。任何人都可以帮我解决这个问题吗?
更新
这是整个页面的代码:
https://pastebin.com/raw/qjnZkUU2
更新代码
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
我感到困惑的是查询如何知道要删除的项目?我是否应该将ID附加到URL以传递ID?
更新
好吧我觉得我明白了....在删除按钮中,我需要回显该行的ID,所以当查询从点击删除按钮运行时,它知道要删除哪个ID正确吗?
分辨
好的。我明白了!
我有一个引用列表项ID的按钮:
echo "<a href='includes/deletelist.php?id=$row[id]'><input class=\"btn btn-danger\" value=Delete style=\"width: 85px;\"></a>
然后我将该ID传递给deletelist.php
if (!isset($_GET['id'])) {
echo 'No ID was given...';
exit;
}
if ($db->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM lists WHERE id = ?";
if (!$result = $db->prepare($sql)) {
die('Query failed: (' . $db->errno . ') ' . $db->error);
}
项目被删除。
答案 0 :(得分:4)
您必须对数据库中的任何操作执行查询
mysqli_query($db, $query);
所以执行删除查询然后再试一次
答案 1 :(得分:3)
您必须执行查询。没有查询执行代码。试试这个
$id = $_GET['id'];
if(isset($_POST["deletelist"])) {
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '$id'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}
答案 2 :(得分:0)
为了删除特定行,我需要做的是在链接/按钮内回显ID。然后,这会将ID传递给所需的PHP以从数据库中删除该行。
回复按钮中的行ID
echo "<a href='includes/deletelist.php?id=$row[id]'><input class=\"btn btn-danger\" value=Delete style=\"width: 85px;\"></a>
用于删除操作行的PHP
<?php
include("db.php");
if (!isset($_GET['id'])) {
echo 'No ID was given...';
exit;
}
if ($db->connect_error) {
die('Connect Error (' . $con->connect_errno . ') ' . $con->connect_error);
}
$sql = "DELETE FROM lists WHERE id = ?";
if (!$result = $db->prepare($sql)) {
die('Query failed: (' . $db->errno . ') ' . $db->error);
}
if (!$result->bind_param('i', $_GET['id'])) {
die('Binding parameters failed: (' . $result->errno . ') ' . $result->error);
}
if (!$result->execute()) {
die('Execute failed: (' . $result->errno . ') ' . $result->error);
}
if ($result->affected_rows > 0) {
echo "The ID was deleted with success.";
} else {
echo "Couldn't delete the ID."; }
$result->close();
$db->close();
header('Location: ../account.php');
?>
这会删除项目行,然后将用户返回到account.php。在这种情况下,页面永远不会真正改变。
答案 3 :(得分:-1)
尝试以下
if(isset($_POST["deletelist"]) && isset($_GET['id']) ) {
$id = $_GET['id'];
$query = "SELECT * FROM lists";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) == 1) {
$query = "DELETE FROM lists WHERE id = '".mysqli_real_escape_string($db,$id)."'";
mysqli_query($db, $query);
} else {
echo "Cannot delete";
}
}