美好的一天。我想删除用户选择的项目。但事实证明用户点击的按钮,第一个数据行正在删除。我卡在这里。请帮忙。
这是我的代码:
HTML
<form method="POST" action="<?php $_PHP_SELF ?>">
<?php
$query = "select * from tblsr";
$request = mysql_query($query)or die(mysql_error());?>
<table class="table table-hover">
<tr>
<th>Softwares</th>
<th>Difficulty</th>
<th></th>
<th></th>
</tr>
<?php while($row = mysql_fetch_array($request)){
?>
<tbody>
<tr class="success">
<td><?php echo $row['Software']; ?></td>
<td><?php echo $row['Difficulty']; ?></td>
<td><input type="submit" class="btn btn-sm btn-success" name="change" value="Change Difficulty"/></td>
<td><input type="submit" class="btn btn-sm btn-danger" name="remove" value="Delete"/></td>
<input type="hidden" name="id[]" value="<?php echo $row['id']; ?>"/>
</tr>
</tbody>
<?php
}
?> </form>
删除查询
if(isset($_POST['remove'])){
$count = count($_POST['id']); //get total number of array element
for ($i = 0; $i < $count; $i++) {
$id = $_POST['id'][$i];
$sql = "Delete FROM tblsr
Where id = '$id'";
$success = mysql_query($sql) or die (mysql_error());
mysql_close();
if ($success == TRUE){
?>
<script>
alert('Deleted.');
window.location.href='manageRequest.php';
</script>
<?php
}
}
}
答案 0 :(得分:1)
您的代码的问题在于您永远不会增加$i
($i++
),并且您的删除查询始终会影响第一行(ID)。您可以在$i++
循环中添加while
来修复它,但我建议您只需执行以下操作,并且不要为循环而烦恼。
删除查询
$rm = $_POST['id'];
if (isset($_POST['remove'])) {
foreach ($rm as $key => $value) {
$rm[$key] = "'".$value."'";
}
$sql = "Delete FROM tblsr
Where id IN(" . implode(",", $rm) .")";
die($sql);
$success = mysql_query($sql) or die(mysql_error());
if ($success) {
?>
<script>
alert('Deleted.');
window.location.href = 'manageRequest.php';
</script>
<?php
}
}
<form method="POST" action="<?php $_PHP_SELF ?>">
<?php
$query = "select * from tblsr";
$request = mysql_query($query) or die(mysql_error());
?>
<table class="table table-hover">
<tr>
<th>Softwares</th>
<th>Difficulty</th>
<th></th>
<th></th>
</tr>
<?php
while ($row = mysql_fetch_array($request)) {
?>
<tbody>
<tr class="success">
<td><?php echo $row['Software']; ?></td>
<td><?php echo $row['Difficulty']; ?></td>
<td>
<input type="checkbox" name="id[]" value="<?php echo $row['id']; ?>"/>
delete
</td>
</tr>
</tbody>
<?php
}
?>
</table>
<button type="submit" name="remove" class="btn btn-success">
delete checked user
</button>
</form>