deleting bulk

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

deleting bulk

Post by elecktricity »

just a quick question, on one page I would have a bunch of checkboxes like so:

Code: Select all

<input type="checkbox" name="val" value="1"><br>
<input type="checkbox" name="val" value="2"><br>
<input type="checkbox" name="val" value="3"><br>
<input type="checkbox" name="val" value="4"><br>
<input type="checkbox" name="val" value="5"><br>
//continues
and I would like to select a few of them and click a delete button which would go to a place like this:

Code: Select all

<?PHP
$val = $_POST['val'];
mysql_query("DELETE FROM pm WHERE val=$val");
?>
which would work fine for deleteing one row but I would like it to delete a few more than that and wouldnt really want to make a huge page with a lot of 'if' statements or anything, im thinking a loop might work or something like that. What would you guys suggest on this one?
User avatar
shiznatix
DevNet Master
Posts: 2745
Joined: Tue Dec 28, 2004 5:57 pm
Location: Tallinn, Estonia
Contact:

Post by shiznatix »

make your html name="val[]"

then do

Code: Select all

foreach ($_POST['val'] as $value)
{
  $sql = '
    DELETE FROM table_name WHERE value = "'.$value.'"
  ';

  $do_query = mysql_query($sql) or die(mysql_error());
}
use that idea and put it into your current script

EDIT: or you can do somthing like

Code: Select all

$sql = 'DELETE FROM table name WHERE ';

foreach ($_POST['val'] as $value)
{
  $sql .= 'row_name ='.$value.', ';
}

//then take the last 5 characters off of $sql which is the space, comma then the word AND

//then do the query, this would make only one mysql query and make for a faster script
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

Post by elecktricity »

sure was a quick reply thanks, ill try it out
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

following shiznatix's logic path of naming, you can do the following as well:

Code: Select all

$vals = implode('\',\'',array_map('intval',$_POST['val']));
$sql = "DELETE FROM `table_name` WHERE `value` IN('{$vals}')";
$do_query = mysql_query($sql) or die(mysql_error());
User avatar
elecktricity
Forum Contributor
Posts: 128
Joined: Sun Sep 25, 2005 8:57 pm
Location: Trapped in my own little world.
Contact:

Post by elecktricity »

well it works great thanks for the help
Post Reply