1

我正在尝试使用复选框项目删除多张图片。但不知何故,图片不会从数据库中删除。

代码运行没有错误。正在重定向页面,但未执行删除查询。

我相信传递图片 id 来查询是有原因的,$List[1]但我真的不明白是什么。看来我做的一切都很好。

感谢您提前提供任何帮助。

那是代码:

<?php
$Connection = mysql_connect( $Host, $User, $Pass ) or die('ERROR: '.mysql_error());
mysql_select_db( $DataBase )or die('ERROR: '.mysql_error());

$Query = "SELECT * FROM pictures WHERE folder_id = ".$FolId.";";
$Picture = mysql_query($Query, $Connection)or die('ERROR: '.mysql_error());
?>
    <form name='Photos' method='POST' >
<?php
   while($List = mysql_fetch_array($Picture)){
     echo "<input type='checkbox' name='photoList[]' value='".$List[1]."'> <span> &nbsp;".$List[4]."</span>";
   }
?>
   <input type='submit' name='Delit' value='DELETE'  >
       </form>

<?php
   if(isset($_POST['Delit'])){
     foreach($_POST['photoList'] as $item){
       $Query="DELETE FROM pictures WHERE picture_id =".$item;
       mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
       header('Location: photos.php');
    }
  }
?>
4

1 回答 1

1

我的猜测是$List[1]不包含您的picture_id. 大概是吧$List[0]

Usingfetch_array不是从数据库中获取数据的好方法 using SELECT *,因为您的列可能会改变位置,并且索引并不能清楚地说明您正在检索哪一列。

尝试使用fetch_assoc来获取与数据关联的列名。

<?php
    // Change `picture_name` below to the name of the column storing your picture's name
    while ($List = mysql_fetch_assoc($Picture)) {
        echo "<input type='checkbox' name='photoList[]' value='{$List['picture_id']}'> <span> &nbsp;{$List['picture_name']}</span>";
    }
?>

另外,试试这个你的DELETE逻辑:

  1. 检查是否photoList已设置(与Delit
  2. 循环遍历您的照片列表并将值转换为(int)以防止 SQL 注入
  3. 使用将 ID 列表连接到逗号分隔的列表中implode
  4. 进行查询,提供照片 ID 列表 - 这比循环执行多个语句DELETE... WHERE IN要快得多DELETE... WHERE =

代码:

<?php
    if (isset($_POST['photoList']) && !empty($_POST['photoList'])) {
        $photoIds = array();
        foreach ($_POST['photoList'] as $photoId) {
            $photoIds[] = (int) $photoId;
        }
        $photoIds = implode(',', $photoIds);
        $Query = "DELETE FROM pictures WHERE picture_id IN ({$photoIds})";
        mysql_query($Query, $Connection)or die("ERROR: ".mysql_error());
        header('Location: photos.php');
    }
?>
于 2013-06-29T12:29:29.277 回答