0

我有存储在 MySQL 数据库中的记录。图像的存储方式如下:

[image1.jpg],[image2.jpg],[image3.jpg]...ETC

我正在使用 SQL Select 查询选择行,然后:

$images = explode(',',$project['images']);

分解每个图像(由 , 分隔)

然后我有:

<?php
        foreach($images as $image)
        {
            $display_image = substr($image, 1, -1);
            ?>
            <tr>
                <td><img src="/img/project-gallery/<?php echo $display_image; ?>" width="160px" /></td>
            </tr>
            <?php
        }
        ?>

我如何在表单中使用 HTML 复选框来删除图像(仅选中),如下所示:

<input type="checkbox" name="images[]" id="images[]" />
4

3 回答 3

0

这是一个非常广泛的问题,所以我只讨论 HTML 部分。

您想在<input>每个图像旁边添加一个元素......像这样:

<tr>
    <td>
        <input name="images_to_delete[]" type="checkbox" value="<?php echo $display_image; ?>" />
        <img src="/img/project-gallery/<?php echo $display_image; ?>" width="160px" />
    </td>
</tr>

你需要用一个<form>标签包围这个表/列表。您还需要一个 php 页面来处理此表单的提交,但我将把它留给您。

在 PHP 中,一旦获得$images_to_delete数组,这是一种可以从原始 $images 字符串中删除图像的方法:

$images = "," . $images . ","; // add comma to beginning and end of list

foreach ($images_to_delete as $image_to_delete) {
    str_replace("," . $image_to_delete . ",", ","); // e.g. replaces ",image1.jpg," with ","
}

$images = substr($images, 1, -1); // remove comma from beginning and end
于 2013-10-14T20:53:30.797 回答
0

我不得不告诉您,您不应该将图像本身存储在数据库中,这被认为是一种不好的做法!将图像保存在磁盘上的某个文件夹中,并在数据库中仅记录有关图像的路径、大小或您想要的任何参数。

您必须首先为每个图像动态分配一个唯一的id,并最终使其看起来像image_id_checkbox_1image_id_checkbox_2等等。

用 PHP 做这样的事情来处理发布请求并只获取检查的图像:

if (isset($_POST['delete_selected_images'])) {
    $index = 0;
    foreach ( $_POST as $key => $value ) {
        if ( substr($key, 0, 18) == 'image_id_checkbox_') {
            if ( $value == 'on' ) {
                deleteImage(str_replace('image_id_checkbox_', '', $key));
                ++$index;
            }
        }
    }

deleteImage函数应该执行以下操作:

function deleteImage( $image_id )
{   
  $image = $config['images_path']. '/' .$image_id. '.jpg';
  if ( file_exists($image) ) {
      @chmod($image, 0777);
      @unlink($image);
  }  
}
于 2013-10-14T21:00:56.213 回答
0

您不应该将图像存储在单个数据库字段中,它是一对多的关系。

您需要创建一个单独的表,以便您可以通过主键唯一地引用每个图像。

CREATE TABLE `product_images` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(255) NOT NULL,
 `src` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
)

更新如果你必须这样做(我建议你不要这样做)

$string = 'image1.jpg,image2.jpg,image2.jpg';
$images = explode(',', $string);

if (isset($_POST['images'])) {
    foreach($_POST['images'] as $name => $value) {
        if (in_array($name, $images)) unset($images[$name]);
    }
    $string = implode(',', array_values($images));
    // update the database with new string
}

foreach($images as $image) {
  echo '<tr><td>';
  printf('<input type="checkbox" name="images[%s]" value="%s"/>', $image, $image);
  printf('<img src="/img/project-gallery/%s"/>', $image);
  echo '</td></tr>';
}
于 2013-10-14T21:06:38.833 回答