Have a piece of code that deletes an entry from a database when a checkbox is selected and the submit button is pressed, using a form. However it will only delete one checkbox, the last one that is selected. My code is. In the form to make checkbox:
<?php
$query = "SELECT user_id, username, CONCAT(first_name,' ',last_name) AS name FROM users ORDER BY first_name ASC";
$result = @mysql_query($query);
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<TR><TD align=\"left\" bgcolor=\"#c0c0c0\"><input type = \"Checkbox\" name=\"UserDelete\" value={$row['user_id']}>{$row['name']} ({$row['username']})<br></td></td>";
}
mysql_close();
?>
And to handle the post:
if (!empty($_POST['UserDelete'])) {
$UserD = escape_data($_POST['UserDelete']);
} else {
$UserD = FALSE;
echo '<p>You have not selected a user to delete<p>';
}
if ($UserD) {
$query="DELETE FROM users WHERE user_id='$UserD'";
$result = @mysql_query( $query );
if (!$result)
{
echo 'cannot run query';
exit;
}
else
echo '<p>has been deleted from the system</p>';
}
}
If anyone has any suggestions to how i could make the code delete every checkbox that a user presses i would be grateful.
Delete item when more than one checkox is selected
Moderator: General Moderators
in your HTML form do it like this...........
name your checkbox so that it will create an array, that is
naming it "UserDelete[]" instead of "UserDelete" will create an array of all selected checkboxes
now the action...
this should do what you looking for

name your checkbox so that it will create an array, that is
naming it "UserDelete[]" instead of "UserDelete" will create an array of all selected checkboxes
Code: Select all
<?php
$query = "SELECT user_id, username, CONCAT(first_name,' ',last_name) AS name FROM users ORDER BY first_name ASC";
$result = @mysql_query($query);
while ($row = mysql_fetch_array ($result, MYSQL_ASSOC)) {
echo "<TR><TD align="left" bgcolor="#c0c0c0"><input type = "Checkbox" name="UserDelete[]" value={$row['user_id']}>{$row['name']} ({$row['username']})<br></td></td>";
}
mysql_close();
?>Code: Select all
<?php // Deletion is Progress
if (isset($_POST['UserDelete']) && (count($_POST['UserDelete']) > 0)) {
mysql_select_db($database, $conn) or die(mysql_error());
$a = $_POST['UserDelete'];
$i = 0;
foreach ($a as $v) {
$deleteSQL = "DELETE FROM users WHERE user_id = $UserDelete[$i]";
mysql_query($deleteSQL, $connPMC) or die(mysql_error());
$i++;
}
}
?>Igoy, I can simplify your code:
Why use foreach if you're not using $v?
Code: Select all
//....skipped
foreach($a as $v){
$deleteSQL = "DELETE FROM users WHERE user_id = $v";
mysql_query($deleteSQL, $connPMC) or die(mysql_error());
}
//....skipped