php - 在 codeigniter 中删除后从文件夹中删除图像

标签 php codeigniter

我不仅想删除数据库中的图像,还想删除文件夹中的图像。

这是我的模型

    public function delete($id)
        {
            if ($this->db->delete("np_gallery", "id = ".$id)) 
            {
            return true;
            }
        }

这是我的 Controller

public function delete_image($id)
{
    $this->np_gallery_model->delete($id);
    $query = $this->db->get("np_gallery");
    $data['records'] = $query->result();
    $this->load->view('admin/gallery/gallery_listing',$data);
}

这是我的观点

<table class="table table-bordered">
            <thead>
                <tr>
                    <td>Sl No</td>
                    <td>Tag</td>
                    <td>Image</td>
                    <td>Action</td>
                </tr>
            </thead>

            <?php 
            $SlNo=1;
                foreach($records as $r)
                {
             ?>
                <tbody>
                    <tr>
                    <?php $image_path = base_url().'uploads';?>
                     <td><?php echo $SlNo++ ; ?></td>
                     <td><?php echo $r->tag; ?></td>
                     <td><img src="<?php echo $image_path; ?>/images/gallery/<?php echo $r->picture;?>" style=" width:35%; height:100px;"/></td>
                     <td><a href="<?php echo site_url() . "/np_gallery/select_content/". $r->id?>" class="fa fa-pencil"></a>&nbsp;&nbsp;
                         <a href="<?php echo site_url() . "/np_gallery/delete_image/". $r->id?>" onClick="return confirm('Are you sure want to delete')" class="fa fa-trash"></a></td>   
                    </tr>
                </tbody>
            <?php } ?>
        </table>

我成功删除了数据库中的数据,但文件夹中的图像没有被删除。

最佳答案

在 Controller 中添加一些额外的代码:

public function delete_image($id)
{
    $image_path = base_url().'uploads/images/gallery/'; // your image path

    // get db record from image to be deleted
    $query_get_image = $this->db->get_where('np_gallery', array('id' => $id));
    foreach ($query_get_image->result() as $record)
    {
        // delete file, if exists...
        $filename = $image_path . $record->picture; 
        if (file_exists($filename))
        {
            unlink($filename);
        }

        // ...and continue with your code
        $this->np_gallery_model->delete($id);
        $query = $this->db->get("np_gallery");
        $data['records'] = $query->result();
        $this->load->view('admin/gallery/gallery_listing',$data);
    }
}

注意:或者,您可以在模型的 delete() 方法中执行此操作。考虑它在哪里更适合您的应用程序需求。

关于php - 在 codeigniter 中删除后从文件夹中删除图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40862932/

相关文章:

phpunit 对实用类发出警告

php - 为什么当我遍历这个数组两次时 PHP 会覆盖值(通过引用,通过值)

php - CodeIgniter Controller 被调用两次

php - CodeIgniter 水印

php - 在 codeigniter 选择查询中获取空数组

php - Krajee bootstrap 如何预览和删除图片?

javascript - 尝试使用 PHP 和 Javascript 创建时间表

php - 如何根据从 html <select> 标记中选择的选项更新 mysql 查询

javascript - 如何让 PHP shuffle 结果在整个 shuffle 过程中一次显示一个

php - 在 CodeIgniter 中使用 foreach 更新表