John Doe John Doe - 5 months ago 10
SQL Question

PHP + MySQL Issue - where did I go so wrong?

Here's the dig. I've looked over and over my code until my mind was numb and still can't figure out where the issue is.

I'm working with a delete feature that works on the backend of a CRM-like application. There is a user list with checkboxes by each registered user inside of a form, and a submit button to run the code to delete the selected users from the database by their ID.

The checkboxes are generated in a foreach loop that populates the table using an array returned from a select query. Each checkbox line for each user is as such:

<input type="checkbox" name="checked[]" value="<?php echo ($userfromforeach['id']); ?>">


The submit button for the form has
(name="deleteusers")
included.

And the actual delete code for the form submission is as follows:

// Delete users by selected as posted by form
if(isset($_POST['deleteusers']))
{
foreach($_POST['checked'] as $user)
{
$query = "
DELETE
FROM $usertable
WHERE id = $user
";

try
{
// These two statements run the query against your database table.
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("MySQL execution error, please contact technical support.");
}

}
// $_POST['checked'] = NULL;
header("Refresh:0");
}


For some reason unknown to me, everything seems to be firing correctly however no records are being deleted from the database. No MySQL error is returned, and when I
print_r
out the
$_POST['checked']
variable it shows as would be expected:

Array ( [0] => 122 [1] => 115 )


^ The values to each key being the user's ID.

Any thoughts? Have I just knuckle-headed up a problem in my own head by missing something entirely elementary? Thanks very much for your help.

Answer
if(isset($_POST['deleteusers'])) <-- submit button with the name "deleteusers"
    {   

        foreach($_POST['checked'] as $user)
        {
            $query = "DELETE FROM $usertable WHERE id = :user";     
            try
            {
                $stmt = $db->prepare($query);
                $stmt->bindParam(':user', $user);
                $stmt->execute();
            }
            catch(PDOException $ex)
            {
                die("MySQL error, blah blah blah...");
            }
        }
    }

and you can run this one in one statement using this query

$query = "DELETE FROM $usertable WHERE id IN (:user)";      

$stmt->bindParam(':user',implode(",",$_POST['deleteusers']));

Comments