Delete multilple marked items
How can I delete multiple items from a list displayed in html.
For example
<ul>
<li>item 1</li>checkbox
<li>item 2</li>
</ul>
<a href="d开发者_Python百科elete.php?ids=checkedids">Delete items</a>
The easy way to do this in PHP is to give all your check boxes the same name, and have that name end with []
:
<input type="checkbox" name="item[]" value="1" />
<input type="checkbox" name="item[]" value="2" />
<input type="checkbox" name="item[]" value="3" />
Then your script gets all the checked values as an array:
if(empty($_REQUEST['item'])) {
// No items checked
}
else {
foreach($_REQUEST['item'] as $id) {
// delete the item with the id $id
}
}
To make this work, you need to put the check boxes into a <form>
, and use a submit button (not a link -- that will not work, unless you start using JavaScript) like this:
<form method="post" target="some/php/script.php">
<input type="checkbox" name="item[]" value="1" />
<input type="checkbox" name="item[]" value="2" />
<input type="checkbox" name="item[]" value="3" />
<input type="submit" name="delete" value="Delete checked items" />
</form>
There are some possible improvements to this (see Crozin's answer), but you should get the basics down first.
First of all you should use a form. You can use checkboxes to select items to delete and then use following query:
DELETE FROM tbl_name WHERE id_col_name IN (1, 2, 3, 4, 5, 6, 7, 8);
HTML form itself could look like following:
<form ...>
...
<li>
<label>Delete item #123 <input type="checkbox" name="delete[123]" />
</li>
...
</form>
Then list of IDs is easily available under $_POST['delete']
array.
精彩评论