在我的代码中,sql查询删除具有相同名称的表中的记录。例如,我有2条相同名称的记录mani&mani。该代码将删除2条记录。
表单代码:
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){?>
<option value="<?php echo $row['username']; ?>"><?php echo
$row['username']; ?></option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete User">
</form>
Sql
<?php
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
mysqli_query($connection, "DELETE FROM `users` WHERE `username` = '$username' ");
echo "User was deleted!";
}
?>
答案 0 :(得分:3)
在这种情况下,您需要选择唯一值,例如ID
尝试这个:
<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){?>
<option value="<?php echo $row['user_id']; ?>"><?php echo
$row['username']; ?></option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete User">
</form>
SQL
<?php
include('connect.php');
if(isset($_POST['delete'])) {
$user_id = $_POST['user_id'];
mysqli_query($connection, "DELETE FROM `users` WHERE user_id = '$user_id' ");
echo "User was deleted!";
}
?>
答案 1 :(得分:2)
是的,您的代码将删除具有匹配名称的行,因为您拥有Query:
DELETE FROM `users` WHERE `username` = '$username'
要删除特定行,您需要使用一些唯一值来引用该行,例如主键!
例如:
如果用户具有EmployeeId
,CustomerId
或StudentRollNo
;您可以在where clause
中使用这些选项。这些技巧是Query中非常基本的内容。