Home > Software design >  How To Delete a Specific User from Database?
How To Delete a Specific User from Database?

Time:05-17

  • 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();
?>

CodePudding user response:

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

$stmt = $conn->prepare('DELETE FROM users WHERE id = ?');
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->close();

CodePudding user response:

Your WHERE condition compares for each row whether the id for the current row matches the id. In other words, the queries compares the field with itself which yields truefor 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.

  • Related