使用PHP从mysql表中使用复选框删除多行

时间:2019-04-03 02:55:45

标签: php html mysql mysqli

我希望通过复选框选中一行或多行后将其删除。但是,即使我选择,它似乎也不会删除任何内容。

这就是我想出的:

<?php
$con=mysqli_connect("localhost","root","","annualdb");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con,"SELECT * FROM asean_japan WHERE agency='Air'");

if(isset($_POST['delete'])) {
  $checkbox = $_POST['checkbox'];

  for($i=0;$i<count((array)$checkbox);$i++) {
    $del_id = $checkbox[$i];
    $sql = "DELETE FROM asean_japan WHERE id='$del_id'";
    $result = mysqli_query($con,$sql);
  }
// if successful, refresh same page 
if($result) {
  echo "<meta http-equiv=\"refresh\" content=\"0;URL=index.php\">";
}
}
?>
<table class='page'>
  <tr>
    <th>Select</th>
    <th>Agency</th>
    <th>FileName</th>
    <th>FileType</th>
    <th>Date Received</th>
    <th>Action</th>
  </tr>
<?php
while($row = mysqli_fetch_array($result))
{
  ?>
  <tr>
    <td align='center' bgcolor='#FFFFFF'><input name='checkbox[]' type='checkbox' value='<?php echo $row['id']; ?>'></td>
    <td><?php echo $row['agency']; ?></td>
    <td><?php echo $row['filename']; ?></td>
    <td><?php echo $row['filetype']; ?></td>
    <td><?php echo $row['date']; ?></td>
    <td><a target='_blank' href='../annual/indicators/" <?php echo $row['filename']; ?>"'>OPEN</a></td>
  </tr>
</table>

<?php
}
?>
<tr>
  <td colspan="4" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" value="Delete"></td>
</tr>
<?php
mysqli_close($con);
?>

我的复选框是否有问题,或者input = delete可能有问题?

2 个答案:

答案 0 :(得分:1)

首先,您需要在while循环外关闭表格标签,然后需要检查数据表中的onclick或是否不定位网址click here this will help you

答案 1 :(得分:0)

    foreach($_POST['checkbox'] as $key =>$val) {
        if($val!='') {
             $sql = "DELETE FROM asean_japan WHERE id='$val'";
             $result = mysqli_query($con,$sql);  
        }
    }