tags:

views:

289

answers:

3

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

A: 

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.

John Conde
Sure... and watch as a webspider wipes out your database.
Ignacio Vazquez-Abrams
This is just a raw example. That's why I put the disclaimer at the end.
John Conde
delete.php should check (server-side) that the user has permission to do the deleting, that'll prevent web spiders doing any damage.
vincebowdren
A: 

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>";
espais
Then you have to look out for malicious users
Charlie Somerville
True, but at least you know who you're dealing with (as long as this area is admin-locked)
espais
+1  A: 

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

RJD22