如何从数据库中删除特定用户?
假设我在我的网站上注册了一个用户,他们现在想删除帐户。
我有一个查询要这样做,但是每次用户使用此功能时,代码都会删除所有用户。
这是我的代码:
<?php
// starts session
session_start();
// set values
$DB_SERVER = 'localhost';
$DB_USERNAME = 'root';
$DB_PASSWORD = '';
$DB_NAME = 'acoolname';
// creates a new connection to the database
$conn = new mysqli($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
// checks connection
if ($conn->connect_error) {
die("ERRO: Falha ao conectar. " . $conn->connect_error);
}
// query to delete the user
$sql = "DELETE FROM users WHERE id = id";
// logout user
if ($conn->query($sql) === true) {
header("location: logout.php");
}else {
echo "ERRO: Falha ao conectar. " . $conn->error;
}
// close connection
$conn->close();
?>
Let's say I have an user registered on my website and they now want to delete the account.
I've a query to do that but every time the user uses this functionality the code deletes all users.
Here is my code:
<?php
// starts session
session_start();
// set values
$DB_SERVER = 'localhost';
$DB_USERNAME = 'root';
$DB_PASSWORD = '';
$DB_NAME = 'acoolname';
// creates a new connection to the database
$conn = new mysqli($DB_SERVER, $DB_USERNAME, $DB_PASSWORD, $DB_NAME);
// checks connection
if ($conn->connect_error) {
die("ERRO: Falha ao conectar. " . $conn->connect_error);
}
// query to delete the user
$sql = "DELETE FROM users WHERE id = id";
// logout user
if ($conn->query($sql) === true) {
header("location: logout.php");
}else {
echo "ERRO: Falha ao conectar. " . $conn->error;
}
// close connection
$conn->close();
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
更多
发布评论
评论(3)
id = id
始终返回true,因此查询确实删除了所有用户。删除特定用户的安全方法是使用准备的语句,以避免使用SQL注入。
类似
id = id
always returns true, so the query indeed deletes all the users.The safe way to delete a specific user is to use prepared statements, in order to avoid SQL injection.
Something like
您的
其中
条件是否对每行进行比较,无论当前行的ID
是否匹配id
。换句话说,查询将字段与本身进行比较,该字段为每个行提供true
。因此,每行都会删除。您必须将第二个
id
替换为包含当前用户的ID值的变量,或使用当前用户的ID。后者容易注射SQL。请参阅这个问题查询,安全。Your
WHERE
condition compares for each row whether theid
for the current row matches theid
. In other words, the queries compares the field with itself which yieldstrue
for every row. Therefore every row gets deleted.You have to replace the second
id
with either a variable that contains the id-value for the current user, or with the id for the current user. The latter is susceptible for SQL injection. See this question how to insert parameters into the query, safely.