0

I have a table filled with data from my database, and i want a button next to it for each specific user to delete that user. but how do i do this?

Here's the code:

<?php               
    include '../includes/db_connect.php';

    $sql = "SELECT * FROM `users`";
    $result = mysql_query($sql, $connection) or die ("Failed to excecute the query $sql on $connection");
?>
<table border=1>
    <tr>
        <th>
        Access lvl
        </th>
        <th>
        Username
        </th>
        <th>
        Email
        </th>
    </tr>
<?php
    while($row = mysql_fetch_array($result))
    {
        echo "</td><td>";
        echo $row['access'];
        echo "</td><td>";
        echo $row['username'];
        echo "</td><td>";
        echo $row['email'];
        echo "</td></tr>";
    }
    echo "</table>";
?>
Fluffeh
  • 33,228
  • 16
  • 67
  • 80
Ixbitz
  • 427
  • 1
  • 5
  • 7
  • 1
    you put a form in the row with a submit button that POSTs the user ID of that user to a script that will then delete that user and redirect you back to the script shown above. – Gordon Sep 06 '12 at 08:36
  • 1
    The fact that all these answers are so horrible just makes me sad. And I trust my personal information to websites written by such people. :( –  Sep 06 '12 at 08:43
  • 1
    If you have got your answer and it works, don't forget to accept it by clicking the check icon next to that answer! – Deep Frozen Sep 06 '12 at 10:18

3 Answers3

2

I do this very often and use jQuery for it. I use the following:

HTML:

<table>
....
<tr>
    <td><span class="delete">Delete me!</span></td>
</tr>
</table>

jQuery:

$(document).on("click", ".delete", function(event)
{
    var sData = "?id=" + $(this).data("id");
    $.ajax({
        url: "pages/delete_script.php",
        type: "POST",
        data: sData,
        success: function(sResult)
        {
            // Process the data you got back from the delete script
            // For example removing the row if successfully deleted:
            if(sResult == "OK")
            {
                $(this).closest("tr").remove();
            }
        },
        statusCode: 
        {
            404: function() 
            {
                alert("page not found");
            }
        }
    });
});

The on() is for the dynamic elements (I do everything with AJAX on that page). Then I put the data I need to send in the correct format and do the AJAX request. In the PHP file could be this:

if($_SERVER['REQUEST_METHOD'] == "POST")
{
    if(isset($_POST['id'])
    {
        mysql_query(
            sprintf('DELETE FROM `table` WHERE `id` = %d', $_POST['id'])
        );
    }
}

Of course it's recommended to use more checks to make sure you remove the right one.

Gordon
  • 312,688
  • 75
  • 539
  • 559
Deep Frozen
  • 2,053
  • 2
  • 25
  • 42
  • 1
    @Gordon thanks for the edit. I always forget that. Luckily I only have personal projects at the moment so nobody can mess with my data. – Deep Frozen Sep 06 '12 at 09:08
0

Let the button redirect to an url like: example.com/user.php?delete=[id]

And fill the [id] with you $row['id']. Now, when you catch the parameter $_GET['delete'] you will get a id. Now you can simply throw this in your DELETE function in MYSQL.

Note:

  • make sure you have security levels set for this action
  • make sure you do not allow strings in this GET
  • make sure you make use of mysql_real_escape_string() !! <- most important
Jelmer
  • 2,663
  • 2
  • 27
  • 45
  • 2
    you want to use POST for that. Not GET. GET is supposed to be idempotent and safe. Also, chances are a crawler going over your site will delete all your users when they index your example.com/user.php?delete=[id] URLs – Gordon Sep 06 '12 at 08:41
  • @Gordon read again. Make sure you have security levels set. And a downvote is not the right choice I think. Since it's an helpfull answer, now he can pick one out of two. Or use POST, or use GET. – Jelmer Sep 06 '12 at 09:13
  • @Gordon also, a crawler will never get here, because if you are a good programmer you have the robots set to "nofollow" in your meta. So a crawler for indexing will NEVER get on that page. It's also highly recommended to have it set to nofollow for better SEO scoring. – Jelmer Sep 06 '12 at 09:14
  • @Gordon why can't he set security levels? Off course he can! He just has to make sure that somebody is logged in, has a certain security level and is allowed to use the action. You never have a "public" delete action. It's always locked by some sort a Authentication component. If not, your website is vulnerable anyway. – Jelmer Sep 06 '12 at 09:16
  • He cannot pick between POST and GET because they have different semantics. [*In particular, the convention has been established that the GET and HEAD methods SHOULD NOT have the significance of taking an action other than retrieval.*](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html). The correct method would be DELETE, but since [HTML form methods only have to support POST and GET](http://www.w3.org/TR/html401/interact/forms.html#h-17.13.1), POST is the right one to use. – Gordon Sep 06 '12 at 09:17
  • "SHOULD", so he "CAN". I don't imply he does, but it's good to understand what the options are. And this conversation is very helpful. As helpful as it is to me. – Jelmer Sep 06 '12 at 09:21
  • [**SHOULD NOT** is clearly defined in RFCs](https://www.ietf.org/rfc/rfc2119.txt) as *This phrase, or the phrase "NOT RECOMMENDED" mean that there may exist valid reasons in particular circumstances when the particular behavior is acceptable or even useful, but the full implications should be understood and the case carefully weighed before implementing any behavior described with this label.* - so yes, he *could* use GET to delete a resource but then you should point out what valid reasons and circumstances would warrant not following the specs in this case. – Gordon Sep 06 '12 at 09:27
  • also see http://stackoverflow.com/questions/786070/why-should-you-delete-using-an-http-post-or-delete-rather-than-get please – Gordon Sep 06 '12 at 09:37
  • That's a decision for him to make. I'm only pointing at the options. That's what SO is all about. When he reads this conversation, he can make up his mind. But at least he knows about it. About the crawler you are probably pointing at: there is no security issue. As long as your back-end is strong, there is no problem at all. And again, simply set the robots to "nofollow". A crawler will never get in your CMS. Impossible, because of the login feature. – Jelmer Sep 06 '12 at 09:41
  • [Never say Never. This has happened in the past](http://thedailywtf.com/Articles/The_Spider_of_Doom.aspx) – Gordon Sep 06 '12 at 09:43
  • I think that is a problem of the programmer. Not the spider/technique itself. His security was not safe by having just a cookie named: isLoggedOn and javascript to redirect. Well, I can turn of javascript and change the content of my cookie as well. So his site was insecure anyway. So like I was pointing: you "can" use it, as long as the back-end is strong. Just to verify, I'm not saying I don't agree with what you are saying. I'm just providing him with information about the subject. – Jelmer Sep 06 '12 at 09:49
0

I would move this away to an AJAX function, passing the variables to a JavaScript function via onClick or data-id="" and using jquery $('element').data('id'); to collect the id and fire it off to another static php file.

Once there you would want to check and sanitise the data that has been passed to the file before committing any user data to the SQL, as mentioned before:

  • Use post as the AJAX method
  • filter_var($var, FILTER_VALIDATE_INT)
  • mysql_real_escape_string

This would feel better for user experience and also remove some of the risk of spiders triggering the action. People will still be able to hack it if your not hot on your security, but it makes it harder, and if you add a status column to you SQL rather than deleting the row you simply change its status, you can easily just bring the data back if ever you got hacked.

gazzwi86
  • 1,019
  • 1
  • 15
  • 35