Search code examples
phpdebuggingbackendsql-delete

How do I change the delete function so it deletes a specific user rather than the whole users list


I have a list of users that are registered to a website and I want to delete a specific user when the delete link is pressed, but I am having an issue where all the users are being deleted once I open the page of the users list.

Here is the users list, where $users is an array that contains the list of users:

<?php foreach($users as $user): ?>
      <tr>
         <th><?= $user->name ?></th>
         <td><?= $user->email ?></td>
         <td><a href="<?php $user->delete()>?">Delete</a></td>
         <td><a href="">Update</a></td>
          </form>
       </tr>
    <?php endforeach?>

Here is the delete function of $user:

  public function delete(){
        $result=$this->db->delete("users","id={$this->id}");
        return $result;
    }

And here is the Database delete function:

public function delete(string $table,string $where,int $limit=1){
        return $this->connection->exec("DELETE FROM $table WHERE $where LIMIT $limit");
    }

How do I make it that specific user is deleted when the link Delete is pressed?!

I tried to change the delete functions but did not achieve a result.


Solution

  • The problem is this piece of code:

     <td><a href="<?php $user->delete()>?">Delete</a></td>
    

    the problem is that when you call the page you are deleting the users directly instead of printing a link to a deletion page.

    you need to create a separete route (or a .php file if you aren't using a framework) such as delete_user.php?user_id={your_user_id} or /{user_id}/delete ( in a framework scenario)

    this route/page has to check if the user passed in to the page exists ad then delete it, by getting the user from the db and than call the delete() method.

    after that your code will be similar to the following in a php framework scenario:

     <td><a href="http://www.example.com/<?php $user->id?>"/delete>Delete</a></td>
    

    or like this in a standalone scenario:

     <td><a href="http://www.example.com/delete_user.php?user_id=<?php $user->id?>">Delete</a></td>