Hi, Guest ~ Login or Register

Checkbox Deletion

Checkbox Deletion

Listed In PHP and MySQL » Systems and Features — Viewing Full Tutorial
Ever used one of those snazzy PM systems where you can check a box (or more than one) and then press a button, then the messages will be deleted?

First of all, you'll need a loop echoing database records (in this case, private messages) - and they'll need to have their unique ID with them.

When you're echoing, add this code:
<input type="checkbox" name="<?=$row[id]?>" id="<?=$row[id]?>" value="<?=$row[id]?>" />
The variable $row[id] is simply an example of whatever the array key would be when you're echoing out the results; i.e. if the ID field in your database was called message_id, and you assigned the variable $r to your mysql_fetch_array statement, it would be $r[message_id].

Now wrap a form round where all the content is (where the checkboxes are etc) - it doesn't matter what the form name is called, but make sure that its method is POST!! Here's my example:
<form name="action" id="action" method="post" action="<?=$_SERVER['PHP_SELF']?>">

<!-- All the PM records and checkboxes here, possibly inside a table or something -->

</form>


Now, before you end the form with </form>, you're going to have to have a submit button which allows you to submit it.

<input type="submit" name="perform" id="perform" value="Delete Selected" />


Now that we've got the HTML bit of it sorted, we're going to do the actual deletion code - which is pretty simple!

Remember, you've got to execute this code before you query the database for the records, otherwise when you've submitted the form, they'll be deleted, but will still show up on the next page.
<?PHP
if($_POST['perform']) {

foreach($_POST as $id) { // This will loop through the checked checkboxes

mysql_query("DELETE FROM yourtable WHERE id='$id' LIMIT 1"); // Change yourtable and id. This deletes the record from the database

}

}
?>


And that's it! You can use this tutorial for things like news systems and tutorial systems too, and just about anything that allows you to delete things.

Working Beta

  1. The Forums
    These are mostly functional. If you see any weird bugs, post a thread about it and an administrator will do something.
  2. Tutorial Writing
    You can now submit tutorials to the brand new management system.
  3. Tutorials Home
    View tutorials by categories and search for them here.
  4. Shoutbox
    See below. Registered users only!

Register

Newest User

Say hi to Lirette25! Lirette25 joined on Monday, 14th July.

Sponsor

Check out Next day fake id

Shoutbox