Reputation: 577
I have the following code, which works to a certain degree:
if(isset($_POST['remove'])) {
$user = $_POST['user'];
$passcode = $_POST['passcode'];
$sql = "SELECT *
FROM admin
WHERE username = '" . $user . "'
and passcode ='".md5($passcode)."'";
$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if($count==0) {
echo "Invalid Credentials";
} else {
include 'config.php';
$cnt=array();
$listCheck = "'" .implode("','", $_POST['checkbox']) . "'";
$sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);
}
Issue is, it only deletes 1 of the selected rows. How do I modify the code so it deletes ALL of the selected rows?
<input type="submit" name="remove" class="btn2" value="Delete Selected">
<div>
<?php
$query1 = "SELECT `name` FROM `customer` ORDER BY `name` ASC ";
$result = mysqli_query($conn, $query1);
echo "<table>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value=" . $row['name'] . "></td>";
echo"</tr>";
}
echo "</table>";
echo "<br>";
?>
</div>
Upvotes: 1
Views: 2804
Reputation: 2693
You can simply use one query to delete all records without the pain of for loop
include 'config.php';
$array = $_POST['checkbox'];
$listCheck = "'" . implode("','", $array) . "'";
echo $sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);
Also there is issue in this code. Replace the below line with your code
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value='" . $row['name'] . "'></td>";
Upvotes: 3
Reputation: 476
This is something that caught my eye
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value" . $row['name'] . "></td>";
Should be
echo '<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="'.$row['name'].'" ></td>';
The value of the checkbox is missing an =
Upvotes: 1
Reputation: 2639
Try the following code:
include 'config.php';
$array = $_POST['checkbox'];
$listCheck = "";
foreach($array as $arr) {
$listCheck .= "'" . urldecode($arr) . "',";
}
$listCheck = substr(trim($listCheck), 0, -1);
echo $sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);
Upvotes: 1
Reputation: 372
better go with foreach( $_POST['checkbox'] as $k => $v)
, it may not always be numbers and even if this way you do not have a loop for each possible in range but only for each selected checkbox.
Also have a look on prepared statements for SQL queries, you do not want to have possible injections.
Besides LIKE
better be replaced by the exact comparison =
.
Upvotes: 1