我尝试使用从MySQL表生成的数据从表中删除行。我看了看这两个问题: 1.如何使用复选框删除数据库结果行 2.使用复选框,PHP和MySQL删除多行。
我需要使用复选框帮助代码删除..
<?php
$sql = mysqli_query($conn, "SELECT * FROM leads ORDER BY lid ASC");
if(mysqli_num_rows($sql) == 0){
echo '<tr><td colspan="8">No Data Entry</td></tr>';
}else{
while($row = mysqli_fetch_assoc($sql)){
echo '<tr>
<td> <input name"checkbox[]" value"'.$row['lid'].'" type="checkbox"></td>
<td>'.$row['name'].'</td>
<td>'.$row['sex'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['company'].'</td>
<td>'.$row['vehicle'].'</td>
</tr>';
}
}?>
取消
<?php
$del_lid = $_POST['checkbox'];
if (isset($_POST['submit'])) {
foreach($del_lid as $value){
$sql = "DELETE FROM leads WHERE lid='".$value."'";
$result = mysqli_query($conn, $sql);
}
}
?>
答案 0 :(得分:2)
复选框缺少等号,因此实际上没有一个值。可以简化sql以使用in
运算符而不是循环。
<table>
<?php
$sql = mysqli_query($conn, "SELECT * FROM leads ORDER BY lid ASC");
if( mysqli_num_rows($sql) == 0 ){
echo '<tr><td colspan="8">No Data Entry</td></tr>';
}else{
while($row = mysqli_fetch_assoc($sql)){
echo '
<tr>
<td> <input name="checkbox[]" value="'.$row['lid'].'" type="checkbox"></td>
<td>'.$row['name'].'</td>
<td>'.$row['sex'].'</td>
<td>'.$row['phone'].'</td>
<td>'.$row['company'].'</td>
<td>'.$row['vehicle'].'</td>
</tr>';
}
}
?>
</table>
<input type="submit" name="delete" class="btn btn-sm btn-primary" value="delete">
<a href="index.php" class="btn btn-sm btn-danger">Cancel</a></td>
</form>
</div>
<?php
$del_lid = $_POST['checkbox'];
if ( isset($_POST['submit'] ) ) {
$sql='delete from `leads` where `lid` in ( ' . implode( ',', $del_lid ). ' )';
$result = mysqli_query($conn, $sql);
}
?>