How to have edit and delete button for each record displayed

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
vlch21
Forum Newbie
Posts: 1
Joined: Thu May 19, 2005 7:21 pm

How to have edit and delete button for each record displayed

Post by vlch21 »

Hi all,

I am a newbie to PHP. I am using mysql as backend. I am retrieving all the records from a table and displaying it.
I want to have a "EDIT" and "DELETE" button for each of the rows while displaying the records so that When I click on "EDIT" button, I should be able to edit the record and when I click on "DELETE" button, I should be able to delete the record.

Please give me some insights on this.

Regards,
Vlch21
Sphen001
Forum Contributor
Posts: 107
Joined: Thu Mar 10, 2005 12:24 pm
Location: Land of the Beaver

Post by Sphen001 »

Hi,

This is a relatively simple question. First, each of your records should have an id. This is very important. Just add a tinyint field onto your table structure and set it to auto increment. Now, in your script, you should have a function that deletes a certain record according to the id number. ex.

Code: Select all

$sql = "DELETE FROM something
  WHERE id=$id";
Then have the edit and delete buttons be links. ex.

Code: Select all

http://www.<?php echo $_SERVER['PHP_SELF']; ?>.com/blah.php?id=somenumber
.

Then, in your script, just get the id number from the URL, and delete the corresponding record.

An example script

Code: Select all

// Already connected to DB
$sql = "SELECT *
  FROM table";

$result = mysql_query($sql);

while ($row = mysql_fetch_assoc($result))
{
  echo "Record: $row['someinfofromdb']";
  echo "Delete: <a href='http://www.yoursite.tld/index.php?id=$row['id']&mode=delete'>Delete</a>";
  echo "Edit: <a href=\'http://www.yoursite.tld/index.php?id=$row['id']&mode=edit'>Edit</a>";
}

if ($_GET['mode'] == 'delete')
{
  $sql = "DELETE
    FROM table
      WHERE id=$_GET['id']";
}

// Do the same for the edit mode if you want to
That's pretty much it. Remember, you'll want to validate any input you get from a user. It's a complicated subject, so search this site. You'll find lots of topics about it.

I hope this gives you an idea how to do this.

Good Luck :D

Sphen001
Post Reply