0

I am writing code, to delete a user from the database when they click the delete button. When the user clicks the button, they run the function "myFunction" which then makes an ajax call to the delete.php page. It should alert when the user is deleted. When I click the button, nothing happens and the user isn't deleted from the database.

This is the script:

<script>
  function myFunction(){
        $.ajax({
          type:'POST',
          url: 'delete.php',
          success: function()
          {
            alert('deleted')
          }


        })
      }

This is delete.php:

<?php 
require_once(__DIR__.'/../includes/db.php');

session_start();

$theuser = $_SESSION['user_data']['user_id'];

if($_POST){
    $stmt = $Conn->prepare ("DELETE * FROM users WHERE user_id =".$theuser);
    $stmt->execute();
}
?>
Marvin
  • 65
  • 1
  • 8
  • 1
    add an `error:` callback to you `$.ajax` to debug the issue - and also check the browser developer tools console for errors – Bravo Dec 15 '20 at 21:19
  • Also, please learn how to use prepared statements in PHP https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php – blex Dec 15 '20 at 21:24
  • 1
    where you set SESSION['user_data']['user_id'] variable? – Giacomo M Dec 15 '20 at 21:24
  • there are no errors, and the sesson user data variable is correct, i have echoed it out, it says the user id succesfully. – Marvin Dec 15 '20 at 21:36
  • 2
    How do you know there are no errors. You are not checking for them. – Jason K Dec 15 '20 at 21:49
  • Are you using MySQLi or PDO? If PDO, what database are you using? – Phil Dec 16 '20 at 01:42

1 Answers1

1

The DELETE statement you have is:

DELETE * FROM users WHERE user_id = ...

Whereas, the proper DELETE syntax is:

DELETE FROM users WHERE user_id = ...

The key difference being the wildcard you have included. (Source)

Moving onto the solution:

<?php 
require_once(__DIR__.'/../includes/db.php');

session_start();

$theuser = $_SESSION['user_data']['user_id'];

if ($_POST && $stmt = $Conn->prepare("DELETE FROM users WHERE user_id = ?")) {
  // Bind the prepared statement params
  $stmt->bind_param("i", $theuser); // assumed user_id is an integer
  
  // Execute the $stmt
  if ($stmt->execute() && $stmt->affected_rows > 0) {
    // Successfully executed, and it affected 1 or more rows
  } else {
    // Failed to execute
  }
  
  // Close $stmt handle
  $stmt->close();
}
?>

Beyond this, it would be expected that you validate $theuser, instead of blindly trusting that it contains a valid user_id.

You should also seek to always implement prepared statements. (Source)

John C.
  • 45
  • 1
  • 5