0

I am building a login system and i want to add a functionality of deleting the account. I created my code but it doesn't work.

    require_once '../db.php';
session_start();
session_regenerate_id();
if (isset($_POST['delete'])) {
    $username = mysqli_real_escape_string($connection, $_SESSION['username']);
    $password = mysqli_real_escape_string($connection, $_SESSION['password']);
    $result = $connection->query("DELETE FROM users WHERE username = '$username'");
    $delete = mysqli_query($connection,$result);
    if (!$delete) {
        echo "Data Not Deleted";
    } else {
        echo "Data Deleted";
    }
}

It is echoing Data not deleted . Any idea why it doesn't work.

  • I think you does to display the mysql error with Data Not Deleted to seen wat's wrong, the username is present in the database ? – Inazo Aug 21 '18 at 15:43
  • Get the error: http://php.net/manual/en/mysqli.error.php – Adam Aug 21 '18 at 15:44
  • 4
    And this : $result = $connection->query("DELETE FROM users WHERE username = '$username'"); does to be : $result = "DELETE FROM users WHERE username = '$username'"; – Inazo Aug 21 '18 at 15:44
  • showing you have an error in sql syntax –  Aug 21 '18 at 15:45
  • 2
    thanks inazo it worked –  Aug 21 '18 at 15:46
  • Add `ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);` to the top of your script. This will force any mysqli_ errors to generate an Exception that you can see on the browser and other errors will also be visible on your browser. – RiggsFolly Aug 21 '18 at 15:56
  • Your script is wide open to [SQL Injection Attack](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Even [if you are escaping inputs, its not safe!](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) Use [prepared parameterized statements](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php) in either the `MYSQLI_` or `PDO` API's – RiggsFolly Aug 21 '18 at 15:56
  • I think you are getting confused with prepared queries. You are running the and then running a query on the result of the first query which will obviously fail. and then testing the result of the incorrect query execution – RiggsFolly Aug 21 '18 at 15:59

2 Answers2

3

Try:

$result = "DELETE FROM users WHERE username = '$username'";
$delete = mysqli_query($connection,$result);

You're running a query in the query otherwise...

Adam
  • 1,294
  • 11
  • 24
0

Try $result = $connection->query("DELETE FROM users WHERE username = $username"); At least, with SELECT it works