-4

I've seen a few questions here already about this topic but I can't see a solution to what I'm trying to do. I have a table and I want to be able to check a checkbox next to each row to have a multiple delete function. I've placed a delete button above the table.

My delete button:

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    <input type="submit" id="staff_list_submit" name="multi_delete" value="Delete"
           onclick="return confirm('Do you really want to do that?')">
</form><br>

My TD containing the checkbox:

        <td style="width: 60px; text-align: center; vertical-align: middle;"><input name="checkbox[]" type="checkbox" value="<?php echo $row['staff_id']; ?>"></td>

My PHP code to handle the delete:

if(isset($_POST['multi_delete']))
{
     $checkbox = $_POST['checkbox'];
     for($i=0;$i<count($checkbox);$i++){
        $del_id = $checkbox[$i];
        echo $del_id;
        $stmt = $conn->prepare("DELETE FROM `Tom`.`staff_details` WHERE `staff_id`=`$del_id`;");
        $result = $stmt->execute();
    }

    if($result) {
        exit(header('Location: staff_multiple_delete.php'));
    }
}

I try to echo $del_id and nothing comes back.

I do get two errors on screen when I click on the Delete button:

Undefined index: checkbox
Undefined index: result

I have been pulling my hair out over this, if there's any help available it would be appreciated. I'm still new to PHP

Thanks

Tom
  • 1,055
  • 1
  • 14
  • 29

1 Answers1

0

It's not tested but I think you ought to be able to do something like the following rather than a loop as you had - which sort of misses the point of prepared statements due to the repeated prepare

if( $_SERVER['REQUEST_METHOD']=='POST' && !empty( $_POST['checkbox'] ) ){

    $ids = implode( ',', $_POST['checkbox'] );
    $sql='delete from `tom`.`staff_details` where `staff_id` in ( :ids )';
    $stmt=$conn->prepare( $sql );

    if( $stmt ){
        $stmt->bindParam( ':ids', $ids );
        $stmt->execute();
    }
}
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Hi RamRaider, I gave it a go but it doesn't seem to recognise that the checkbox has been selected. All examples I've seen have suggested that layout for the checkbox. – Tom Jun 20 '17 at 08:23