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();
}
?>
6
  • 1
    add an error: callback to you $.ajax to debug the issue - and also check the browser developer tools console for errors Commented Dec 15, 2020 at 21:19
  • Also, please learn how to use prepared statements in PHP php.net/manual/en/mysqli.quickstart.prepared-statements.php Commented Dec 15, 2020 at 21:24
  • 1
    where you set SESSION['user_data']['user_id'] variable? Commented Dec 15, 2020 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. Commented Dec 15, 2020 at 21:36
  • 2
    How do you know there are no errors. You are not checking for them. Commented Dec 15, 2020 at 21:49

1 Answer 1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.