我有以下代码,它在某种程度上起作用:
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);
}
问题是,它只删除所选行中的一行。如何修改代码以删除所有选定的行?
<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>
答案 0 :(得分:3)
您可以简单地使用一个查询来删除所有记录,而不必担心for循环
include 'config.php';
$array = $_POST['checkbox'];
$listCheck = "'" . implode("','", $array) . "'";
echo $sql6 = "DELETE FROM `customer` WHERE `name` IN ($listCheck)";
$delete = mysqli_query ($conn,$sql6);
此代码中也存在问题。将以下代码替换为您的代码
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value='" . $row['name'] . "'></td>";
答案 1 :(得分:0)
最好使用foreach( $_POST['checkbox'] as $k => $v)
,它可能并不总是数字,即使这样,您也没有针对范围内每个可能的循环,但仅针对每个选定的复选框。
另请查看SQL查询的预准备语句,您不希望有可能的注入。
除了LIKE
之外,最好用完全比较=
替换。
答案 2 :(得分:0)
请尝试以下代码:
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);
答案 3 :(得分:0)
这引起了我的注意
echo "<td><input name='checkbox[]' type='checkbox' id='checkbox[]' value" . $row['name'] . "></td>";
应该是
echo '<td><input name="checkbox[]" type="checkbox" id="checkbox[]" value="'.$row['name'].'" ></td>';
复选框的值缺少=