0

我的库存中有一个汽车清单,每辆汽车最多可以有 12 张照片。如果我愿意,我可以成功擦除汽车,但我遇到的问题也是擦除图片。

所以我可以这样查询:

$pictures = "picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9, picture10, picture11, picture12";
$data = mysql_fetch_assoc(mysql_query("SELECT $pictures FROM `auto` WHERE `auto_id` = $autoid"));

使用$data变量,我可以像这样访问图片的名称echo $data['picture1'];

我试图让 for 循环遍历每张图片,只要 db 中的字段不为空,就从数据中创建这些文件路径的数组并循环遍历数组,使用unlink()?

SO FAR SOLUTION [有效但需要改进?]

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

    $pictures = "picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9,
    picture10, picture11, picture12";
    $data = mysql_fetch_assoc(mysql_query("SELECT $pictures FROM `auto` WHERE `auto_id` = $autoid"));
    $a = 1;
    while ($a <= 12)
    {
        $picturepath = $data['picture'.$a];
        if (empty($picturepath) !== true)
        {
            unlink('../../' . $picturepath);
        }
        $a++;
    }

    mysql_query("DELETE FROM `auto` WHERE `auto_id` = $autoid");
    header('Location: ../../admin.php?manage_vehicles');
    exit();
}
4

2 回答 2

0

在查询后添加一个 foreach 循环。

    foreach($data AS $photo)
    {
         if (!empty($photo) && file_exists($photo)) unlink($photo);
    }

更新答案,添加 file_exists()

于 2013-07-24T23:13:12.720 回答
0

您可以执行一个 for 循环,将循环索引值附加到字符串“图片”,然后使用它来访问 $data[] 元素。当您可以简单地执行以下操作时,为什么还要打扰:

foreach ($data as $picname) {
  if (file_exists($picname) && is_file($picname)) unlink($picname);
}

简单的。

好的,让我们看一下:这是一件小事,但我更喜欢使用 array_key_exists 而不是 isset,如果不使用 foreach,我将使用 for 循环,并且不必在查询字符串中规定图片 [n] 列。那么怎么样:

if (array_key_exists('delete',$_POST))
{
    // not needed
    // $pictures = "picture1, picture2, picture3, picture4, picture5, picture6, picture7,
    // picture8, picture9, picture10, picture11, picture12";
    // if $autoid is an integer, you can reduce the risk of sql injection by intval()
    // otherwise look at using preg_replace or using mysqli functions with prepare and bind_params
    $autoid=intval($autoid); 
    $res=mysql_query("SELECT * FROM `auto` WHERE `auto_id` = $autoid"));
    if (!($res===false))
    {
      $data = mysql_fetch_assoc($res);
      if (!($data===false))
      {
        for ($i=0; $i<=12; $i++)
        {
          $pic_col="picture$i";
          if (!array_key_exists("$pic_col",$data) || !strcmp(trim($data["$pic_col"]))) continue;
          $picname = '../../'.trim($data["$pic_col"]);
          if (file_exists($picname) && is_file($picname)) unlink($picname);
        }
      }
    }
    mysql_query("DELETE FROM `auto` WHERE `auto_id` = $autoid");
    header('Location: ../../admin.php?manage_vehicles');
    exit();
}
于 2013-07-24T23:16:20.033 回答