Page 1 of 1

Deleting from database by checking multiple checkboxes

Posted: Mon Oct 22, 2007 12:50 pm
by sparky753
I have a form that has images that are displayed from a database. Beside each image, I have a checkbox.

How do I set things up so that when i check multiple checkboxes and click Submit, the corresponding image/record will be deleted from the database? Please help....

Posted: Mon Oct 22, 2007 1:46 pm
by Rovas
It' s like this:

Code: Select all

if (isset($_POST["Submit"]))
{
  if (isset($_POST["FirstCheckbox"]) ){
    //execute the mysql code for deletion of image : DELETE TableName.NameOfColumn FROM TableNAme WHERE NameOfColumn='NameOfImage'  
      
  }
  if (isset($_POST["SecondCheckbox"])){// exactly like the one before} 
   
}
You can use case.. switch if there are more than 3 checkboxes or repetive structure but the logic is the same.

Posted: Mon Oct 22, 2007 2:53 pm
by sparky753
My checkboxes are going to be dynamically generated so the name is going to be:

Code: Select all

<input type='checkbox' name='deleteimg[]' value='1'>

Posted: Mon Oct 22, 2007 3:04 pm
by Rhys.mataira
and by that u mean for example the names will be
deleteimg[0], deleteimg[1], deleteimg[2], deleteimg[3]
??

Posted: Mon Oct 22, 2007 3:22 pm
by sparky753
Yes. Somebody suggested using the implode statement and that worked like a charm.

Code: Select all

$ids = implode(', ', $_POST['chk']);
$sql = "DELETE FROM table_name WHERE ID IN ($ids)";
Thanks for all of your help...

Posted: Mon Oct 22, 2007 3:30 pm
by Rhys.mataira
well u could do this

Code: Select all

$sql="DELETE FROM 'yourtable' WHERE ";
$findme='eleteimg';
$counter=0;
foreach($_POST as $mystring => $value){
	$strSearch = strpos($mystring, $findme);
	if(!empty($strSearch)) {
		$sql .= (!$counter) ? "'id' =".$value : " , 'id' =".$value ;
		$counter++;
	}
}
Now in the 15 minutes ive browsed this site ive found a much better solution which i think might have been more on track with your original ideas

Code: Select all

$sql="DELETE FROM 'yourtable' WHERE ";
$counter=0;
foreach($_POST['deleteimg'] as $value){
	$sql .= (!$counter) ? "'id' =".$value : " , 'id' =".$value ;
	$counter++;
}
and all you do for your html side of things is name your deleteimg inputs deleteimg[]

Posted: Mon Oct 22, 2007 3:56 pm
by sparky753
That's terrific!! Thanks so much for all your help, and for going through so much trouble to give me a very good solution!! I truly appreciate it...

Thanks again...