I am trying to figure out how I can delete multiple records using check boxes. I have a table on my page that gets the data from the database. The first column for each row has a check box that looks like the following:
<input type="checkbox" name="checked[]" value='.$row['UserId'].' class="checkbox" />
My code looks like the following:
<?php
// get required includes
require_once(ROOT_PATH.'connections/mysql.php');
require_once(ROOT_PATH.'admin/controls/users_az/error_messages.php');
// declare variables
$msg = '';
// ------------------------------------------------------------------
// DELETE SELECTED USERS
// ------------------------------------------------------------------
if(isset($_POST['btnDeleteSelected']) && isset($_POST['checked']))
{
$checked = array_map(mysqli_real_escape_string($conn, $_POST['checked']));
$list = "'" . implode("','", $checked) . "'";
$delete_selected = mysqli_query($conn, "DELETE FROM users WHERE UserId IN ($list)")
or die($dataaccess_error);
if($delete_selected)
{
$msg = mysqli_affected_rows($delete_selected).' '.$msg_success;
}
}
elseif(isset($_POST['btnDeleteSelected']) && !isset($_POST['checked']))
{
$msg = $msg_error;
}
?>
Problem: Naturally this does not work. This is the first time I am attempting to do this.
Question: Am I on the right path with this? How do I need to modify this to make it work?
This will yield an error:
$checked = array_map(mysqli_real_escape_string($conn, $_POST['checked']));
Because array_map
wants a callback as the first, and an array as the second argument. The rest of the setup is pretty good, but as mysqli_real_escape_string
needs a connection, array_map or array_walk aren't that convenient, you might try a normal foreach
loop. Alternatively, if the id's are always integers:
$checked = array_map('intval',$_POST['checked']);
... and drop the quotes around the values in the implode statement (try to feed mysql integers for integer columns, strings for other (char/date/blob/text) columns).