简体   繁体   中英

Best way to delete mysql rows from html page - delete link and php

I'm returning all rows in a table with a while statement and PHP. the rows indicate a list of items. I'd like to include delete links next to each item so users can delete the entries. I'm trying to figure how to go about it in PHP. Can anyone help me write the script.. I'm using procedural.. not OOP. I'm thinking the link takes users to a process page and back, but I'm not gonna be aware of the entries beforehand, it's all dynamic and the list is always changing.

thanks in advance

Best and save practice is using checkboxes. Google doesn't spider them, users can't put in malicious code easily and it doesn't refresh the page for every delete:

HTML sample:

while ($row = mysql_fetch_assoc($items))
{
    echo '<input name="delete['.$row['id'].']" type="checkbox">';
}

PHP processing sample:

$delete = $_POST['delete'];

foreach($delete as $id = $value)
{
    $id = mysql_real_escape_string($id);
    mysql_query("DELETE FROM table_name WHERE id = $id");
}

Something like this should do the job nicely

Definitely take a look at Ignacio's comment. Since webspiders are able to follow links...naturally they will hit your delete link and destroy any data you have in there.

I'd recommend making it a tiny form with a submit button instead of a link.

Something along the lines of

echo "<form id='form_$id' method='post'>" ..
      <input type='hidden' name='id' value='$id' /> ..
      <input type='submit' name='submit_$id' value='delete' /> ..
      </form>";

This is pretty straight forward. Just create a URL with the ID of the row you wish to delete as a parameter of that URL. Then when that link is clicked get the ID from the query string and do your database work.

To create the link:

<?php
// Do query here
while ($row = mysql_fetch_assoc($resource_id))
{
     echo "<a href="delete.php?id={$row['id']}">Delete row</a>;
}
?>

To process the delete request:

<?php
    $id = $_GET['id'];
    mysql_query("DELETE FROM table_name WHERE id = {$id}");
?>

Naturally you need to do data validation and stuff but this should give you the idea.

Wouldn't using Javascript to delete the record be a possible way to prevent web spiders from following the link?

For example, doing something like:

<a href="#" id="delete_link" rel="3">Delete</a>

<script>
  $('#delete_link').click(function() {
    document.location.href = "delete.php?id=" + $(this).attr('rel');
  });
</script>

This should be fine if web spiders do not follow Javascript links...

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