我想在管理员点击下图中的“删除”按钮时删除帐户:
https://www.dropbox.com/s/ytqgdgk2c581yn3/Capture.JPG
Delete.php
<?php
$con=mysqli_connect("localhost","root","123","data1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="Delete from users where id=id";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
echo "Record Deleted";
header("Refresh:3; url=admin.php");
mysqli_close($con);
?>
这是我在图片中使用的代码
admin.php的
<?php
$con=mysqli_connect("localhost","root","123","data1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM users");
echo "<table align='center' id='rounded-corner'>";
echo "<thead>
<tr>
<th scope='col' class='rounded-company'>ID</th>
<th scope='col' class='rounded-company'>Username</th>
<th scope='col' class='rounded-q1'>Password</th>
<th scope='col' class='rounded-q2'>Filter Status</th>
<th scope='col' class='rounded-q3'>Led Status</th>
<th scope='col' class='rounded-q4'>Heater Status</th>
<th scope='col' class='rounded-q4'>Edit</th>
<th scope='col' class='rounded-q4'>Delete</th>
</tr>
</thead>";
echo "<tfoot>";
echo "</tfoot>
<tbody>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>" . $row['filter_st'] . "</td>";
echo "<td>" . $row['led_st'] . "</td>";
echo "<td>" . $row['heat_st'] . "</td>";
echo "<td>" . '<a class="button_green" href="edit.php">Edit</a>' . "</td>";
echo "<td>" . '<a class="button_red" href="delete.php">Delete</a>' . "</td>";
echo "</tr>";
}
echo "</tbody>
</table>";
mysqli_close($con);
?>
答案 0 :(得分:3)
首先要将用户ID作为参数添加到编辑/删除操作中(但请确保在这些文件中强制执行授权);对于删除,这将给出
echo "<td>" . '<a class="button_red" href="delete.php?id=" . $row['id'] . ">Delete</a>' . "</td>";
现在,在Delete.php
文件中,您需要从GET
参数中获取用户ID
$id = intval($_GET['id']);
请注意,您需要验证并取消查询从查询参数(在$_GET
数组中)恢复的数据,当然还要确保只有授权用户才能有效地执行这些操作(因此您需要检查如果请求删除的用户已通过身份验证并具有适当的授权,则您不能只假设只有管理员才知道该网址。
现在正如其他人指定的那样,您需要正确计算删除查询
"DELETE FROM users where id = " . $id;
或准备好的陈述
$stmt = mysqli_prepare($con, "DELETE FROM users where id = ?;");
mysqli_stmt_bind_param($stmt, 'd', $id); // you bind one numeric parameter ('d') with $id as value
mysql_stmt_execute($stmt);
编辑:该死的,只是看到这个问题我通过3个月大的“相关”问题得到了...
答案 1 :(得分:2)
$sql="Delete from users where id=id";
id
未定义。
答案 2 :(得分:2)
您目前的方式,它将删除您的所有用户。因为对于每个用户,id将等于id。
需要更改为
$sql="Delete from users where id=$id";
这样它只会删除id = $ id
的用户答案 3 :(得分:2)
没有足够的信息可以提供完整的答案,但有一件事要看这部分:
$sql="Delete from users where id=id";
实际上,id总是等于它自己,所以你会有效地删除每个用户。
您需要区分ID
$id = 10; //(get the id somehow)
$sql="Delete from users where id=". $id;
或更简单
$id = 10; //(get the id somehow)
$sql="Delete from users where id=$id";