简体   繁体   中英

removing row from database through delete button in a php table

I'm trying to make a little control panel so I can add and delete rows in a database. I've already made the adding part work but I'm having some trouble with the deleting.

The page shows every row in a table and I've added a delete button behind it.

This are the codes I have

This is the code that makes the table:

<table class='col-sm-6 fixed_headers'>
<thead>
<tr>
<th>Username</th>
<th>Password</th>
<th>Email</th>
</tr>
</thead>
<tbody style='height:250px; overflow:auto;'>";

while($row = mysqli_fetch_array($result))
{
 "<tr class=". $row['ID'] . ">";
 echo "<td>" . $row['uname'] . "</td>";
 echo "<td>" . $row['pass'] . "</td>";
 echo "<td>" . $row['email'] . "</td>";
 echo "<td><input type='submit' class='button' id=".$row['ID'] . " value='del'></td>";
 echo "</tr>";
 }
echo "</tbody>
 </table>";
?>  

Here is the ajax code:

<script type="text/javascript">
$(document).ready(function(){
$('.button').click(function(){
    var btnID = $(this).id;


  jQuery.ajax({
        type: "POST",
        url: "php/delete.php",
        data:  {id :btnID}
    }).done(function(result){
    if(result== "succes"){
        $('#error').remove();
        $('#succes').html("Het account is verwijderd. ");

    }else {
        $('#error').empty();
        $('#error').html("Er is een fout opgetreden.<br/> Probeer opnieuw! ");
    }
    });
  });

});
</script>

and here is the delete.php:

$id =  mysql_real_escape_string($_POST['id']);

$delete = "DELETE FROM `xxx`.`xxx` WHERE `xxx`.`ID` = '$id'"; 
$del = mysql_query($delete);

if ($del)
{
    echo "succes";

}
else
{
    echo "error";
    // close connection 
    mysql_close();
}
?>

when I press the delete button, I do get the succes message but the row hasn't been deleted of my database.

I have been trying to fix this, but I can't seem to make it work

(left out my db connect code)

My Advice to you, is to NEVER delete from your database.

Instead, add a boolean variable to your table, which is by default set to '1' and whenever you want to "delete" a row, Set your bool to '0'.

When you query your table to show on your page, query WHERE boolVariable = '1'.

For security reasons, this is the best approach, and make sure to remove the "delete" priviledge from the Db user you're using to connect to your database


One more thing, stop using mysql_query, and use mysqli_query as mysql_ is deprecated

source: The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

将$(this).id更改为$(this).attr('id')修复它

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM