Question

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?

Was it helpful?

Solution

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).

OTHER TIPS

Just check that every element of your array is an integer (with ctype_digit()) for instance, and then you can use implode without quotes, like this:

$list = implode(", ", $checked);

With PHP >= 5.3 you can use an anonymous function:

$checked = array_map(function($s) use ($conn) { return mysqli_real_escape_string($conn, $s); }, $_POST['checked']);

Otherwise you could either callback to a user defined function:

$checked = array_map('myescape', $_POST['checked']);
function myescape($s)
{
    global $conn;
    return mysqli_real_escape_string($conn, $s);
}

or just manually loop.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top