mysql - 仅当有新图像要上传时才取消链接

标签 mysql codeigniter image-uploading image-upload

问题:

你好,

我有一个编辑页面,使客户能够更新销售信息,我想做的是,如果未上传新图像,它将保留原始图像,但如果上传新图像,它将删除旧图像来自数据库行的图像并从服务器取消链接文件,

但我不确定如何将其应用到下面的代码中。如何使文件字段不再是必需的?

更新:

罗斯,

我已经完成了以下操作,但如果图像错误,我仍然会收到销售更新+消息,我怎么可能只在需要时出现错误?

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Editsale extends CI_Controller {

    function __construct() {
    parent::__construct();

    }

    function index() {
    echo 'index';
    $id = $this->uri->segment(4);
    # Set Main Page Data
        $data['title'] = 'Edit Sale:';
        $data['sales_pages'] = $this->sales_model->getSalesPages();
        $data['cms_pages'] = $this->navigation_model->getCMSPages();
        $data['sale']= $this->sales_model->getSalesContent($id);

         #Set The Validation Rules
                $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
                $this->form_validation->set_rules('location', 'Location', 'trim|required|xss_clean');
                $this->form_validation->set_rules('bedrooms', 'Bedrooms', 'trim|numeric|required|xss_clean');
                $this->form_validation->set_rules('bathrooms', 'Bathrooms', 'trim|numeric|required|xss_clean');
                $this->form_validation->set_rules('condition', 'Condition', 'trim|required|xss_clean');
                $this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
                $this->form_validation->set_rules('price', 'Price', 'trim|required|xss_clean');

                if($this->form_validation->run()) #If Valid Run
                {
                    $content = array(   
                        'name' => $this->input->post('name', TRUE), 
                        'location' => $this->input->post('location', TRUE), 
                        'bedrooms' => $this->input->post('bedrooms', TRUE), 
                        'bathrooms' => $this->input->post('bathrooms', TRUE), 
                        'condition' => $this->input->post('condition', TRUE), 
                        'description' => $this->input->post('description', TRUE), 
                        'price' => $this->input->post('price', TRUE)
                    );

                    if($_FILES['userfile']['error'] != 4) 
                    {  
                        //Set File Settings 
                        $config['upload_path'] = 'includes/uploads/sales/'; 
                        $config['allowed_types'] = 'jpg|png'; 
                        $config['remove_spaces'] = TRUE ;
                        $config['overwrite'] = TRUE;
                        $config['max_size'] = '1024';
                        $config['max_width'] = '1024'; 
                        $config['max_height'] = '768'; 

                        $this->load->library('upload', $config);

                        //Continue and resize the image
                        $data = array('upload_data' => $this->upload->data());

                        $config['image_library'] = 'GD2';
                        $config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
                        $config['new_image'] = 'includes/uploads/sales/thumbs/';
                        $config['create_thumb'] = 'TRUE';
                        $config['thumb_marker'] ='_thumb';
                        $config['maintain_ratio'] = 'FALSE';
                        $config['width'] = '200';
                        $config['height'] = '150';

                        $this->load->library('image_lib', $config);
                        $this->image_lib->resize(); 

                        if(!$this->upload->do_upload()) //Process the upload function and uploads image
                        {
                            $data['message'] = array('imageError' => $this->upload->display_errors()); // Capture any $config errors and output them
                        }
                        else
                        {

                            $file_info = $this->upload->data(); //Returns an data array 

                            // Append image data to content array in preparation for db update
                            $content['imagename'] = $file_info['file_name'];
                            $content['thumbname'] = $file_info['raw_name'].'_thumb'.$file_info['file_ext'];
                        }   
                    }   

                    // After everything, update DB

                    if($this->sales_model->updateSale($id, $content))
                    {
                        $data['success'] = TRUE;
                    }
                    else
                    {
                        $data['success'] = FALSE;
                    }


             } # End Form Validation
        $data['cms_pages'] = $this->navigation_model->getCMSPages();
        $data['sales_pages'] = $this->sales_model->getSalesPages($id);
        $data['sale']= $this->sales_model->getSalesContent($id);
        $data['content'] = $this->load->view('admin/editsale', $data, TRUE); #Loads the "content"
        $this->load->view('admintemplate', $data); #Loads the given template and passes the $data['content'] into it   

    } # End Index Function
} # End Controller

查看:

<?php
//Setting form attributes
$formEditSale = array('id' => 'editSale', 'name' => 'editSale');
$formEditSaleName = array('id' => 'name', 'name' => 'name');
$formEditSaleLocation = array('id' => 'location', 'name' => 'location');
$formEditSaleBedrooms = array('id' => 'bedrooms','name' => 'bedrooms');
$formEditSaleBathrooms = array('id' => 'bathrooms','name' => 'bathrooms');
$formEditSaleCondition = array('id' => 'condition','name' => 'condition');
$formEditSaleImage = array('id' => 'userfile', 'name'=> 'userfile');
$formEditSalePrice = array('id' => 'price','name' => 'price');
$formEditSaleDescription = array('id' => 'description','name' => 'description');
$formEditSaleSubmit = array('id' => 'submit', 'name'=> 'submit');
?>

<div id ="formLayout" class="form">
    <?php
    if($success == TRUE) {
    echo '<section id = "validation">Sale Updated</section>';   
    }

    echo '<section id = "validation">'.$message['imageError'].'</section>';
    ?>
    <h4>You are editing sale: <?= $sale[0]['name']; ?></h4>
<?php echo form_open_multipart('admin/editsale/index/'.$sale[0]['id'].'/'.url_title($sale[0]['name'],'dash', TRUE),$formEditSale); ?>
<?php echo form_fieldset(); ?>

<label><?php echo form_label('Name:','name'); ?> <span class="small">Required Field - Text</span></label>
<?php echo form_input($formEditSaleName, $sale[0]['name']); ?>
<div id="error"><?php echo form_error('name'); ?></div>

<label><?php echo form_label('Location:','location');?> <span class="small">Required Field - Text</span></label>
<?php echo form_input($formEditSaleLocation, $sale[0]['location']);?>
<div id="error"><?php echo form_error('location'); ?></div>

<label><?php echo form_label('Bedrooms: ','bedrooms');?> <span class="small">Required Field - Number</span></label>
<?php echo form_input($formEditSaleBedrooms, $sale[0]['bedrooms']);?>
<div id="error"><?php echo form_error('bedrooms'); ?></div>

<label><?php echo form_label('Bathrooms: ','bathrooms');?> <span class="small">Required Field - Number</span></label>
<?php echo form_input($formEditSaleBathrooms, $sale[0]['bathrooms']);?>
<div id="error"><?php echo form_error('bathrooms'); ?></div>

<label><?php echo form_label('Condition: ','condition');?> <span class="small">Required Field - Text</span></label>
<?php echo form_input($formEditSaleCondition, $sale[0]['condition']);?>
<div id="error"><?php echo form_error('condition'); ?></div>

<label><?php echo form_label('Price: ','price');?> <span class="small">Required Field - Number</span></label>
<?php echo form_input($formEditSalePrice, $sale[0]['price']);?>
<div id="error"><?php echo form_error('price'); ?></div>

<label><?php echo form_label('Image: ','userfile');?> <span class="small">1MB Max JPG/PNG</span></label>
<?php echo form_upload($formEditSaleImage);?>
<div id="error"><?php echo form_error('userfile'); ?></div>

<label><?php echo form_label('Description: ','description');?> <span class="small">Required Field - Text</span></label>
<div id="error"><?php echo form_error('description'); ?></div>
<?php echo form_textarea($formEditSaleDescription, $sale[0]['description']);?>
<script type="text/javascript">CKEDITOR.replace('description');</script>

<?php echo form_submit($formEditSaleSubmit,'Submit Edit');?>
<?php echo form_fieldset_close(); ?>
<?php echo form_close(); ?>
</div>

Controller :

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Editsale extends CI_Controller {

    function __construct() {
    parent::__construct();

    }

    function index() {
    $id = $this->uri->segment(4);
    # Set Main Page Data
        $data['title'] = 'Edit Sale:';
        $data['sales_pages'] = $this->sales_model->getSalesPages();
        $data['cms_pages'] = $this->navigation_model->getCMSPages();
        $data['sale']= $this->sales_model->getSalesContent($id);

         #Set The Validation Rules
                $this->form_validation->set_rules('name', 'Name', 'trim|required|xss_clean');
                $this->form_validation->set_rules('location', 'Location', 'trim|required|xss_clean');
                $this->form_validation->set_rules('bedrooms', 'Bedrooms', 'trim|numeric|required|xss_clean');
                $this->form_validation->set_rules('bathrooms', 'Bathrooms', 'trim|numeric|required|xss_clean');
                $this->form_validation->set_rules('condition', 'Condition', 'trim|required|xss_clean');
                $this->form_validation->set_rules('description', 'Description', 'trim|required|xss_clean');
                $this->form_validation->set_rules('price', 'Price', 'trim|required|xss_clean');

                if($this->form_validation->run())
                {
                //Set File Settings 
                $config['upload_path'] = 'includes/uploads/sales/'; 
                $config['allowed_types'] = 'jpg|png'; 
                $config['remove_spaces'] = TRUE;
                $config['overwrite'] = TRUE;
                $config['max_size'] = '1024';
                $config['max_width'] = '1024'; 
                $config['max_height'] = '768'; 

                $this->load->library('upload', $config);

                if(!$this->upload->do_upload())
                {
                    $data['message'] = array('imageError' => $this->upload->display_errors());
                }
                else{
                        $data = array('upload_data' => $this->upload->data());
                        $data['success'] = TRUE;
                        $config['image_library'] = 'GD2';
                        $config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
                        $config['new_image'] = 'includes/uploads/sales/thumbs/';
                        $config['create_thumb'] = 'TRUE';
                        $config['thumb_marker'] ='_thumb';
                        $config['maintain_ratio'] = 'FALSE';
                        $config['width'] = '200';
                        $config['height'] = '150';

                        $this->load->library('image_lib', $config);
                        $this->image_lib->resize();

                    $file_info = $this->upload->data();

                    #Lets Set What We Are Sending To The DB
                $this->db->escape($content);

                $content = array(   
                    'name' => $this->input->post('name', TRUE), 
                    'location' => $this->input->post('location', TRUE), 
                    'bedrooms' => $this->input->post('bedrooms', TRUE), 
                    'bathrooms' => $this->input->post('bathrooms', TRUE), 
                    'condition' => $this->input->post('condition', TRUE), 
                    'description' => $this->input->post('description', TRUE), 
                    'price' => $this->input->post('price', TRUE), 
                    'imagename' => $file_info['file_name'],
                    'thumbname' => $file_info['raw_name'].'_thumb'.$file_info['file_ext']
                );          

                   $this->sales_model->updateSale($id, $content);

                   }# else end

             } # End Form Validation
        $data['cms_pages'] = $this->navigation_model->getCMSPages();
        $data['sales_pages'] = $this->sales_model->getSalesPages($id);
        $data['sale']= $this->sales_model->getSalesContent($id);
        $data['content'] = $this->load->view('admin/editsale', $data, TRUE); #Loads the "content"
        $this->load->view('admintemplate', $data); #Loads the given template and passes the $data['content'] into it   
    } # End Index Function
} # End Controller

型号:

function updateSale($id, $content) {
            $this ->db->where('id', $id);  
            $update = $this->db->get('sales');
            $row = $update->row_array();
            if($update->num_rows() > 0) {
                #lets delete the image
                unlink("/includes/uploads/gallery/".$row['imagename']);
                #lets delete the thumb.
                unlink("/includes/uploads/gallery/thumbs/".$row['thumbname']);

                $this->db->update('sales', $content);
            } # End IF
        } # End Update

最佳答案

您必须重新修改 if(!$this->upload->do_upload() 位,因为如果没有文件,它总是会失败。

那么怎么样...

if($_FILES['userfile']['error']==4) {
    // no file was selected
} else {

   // you can upload!
}

// carry on.

因此,我们使用它的错误代码4来检查$_FILES中是否存在文件,以确定它是否为空。

您仍然可以使用 CI 的 do_upload() 但首先检查是否存在,而不是使用 CI,否则您的代码将始终因 CI 的文件验证工作方式而失败。

关于mysql - 仅当有新图像要上传时才取消链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5909745/

相关文章:

vue.js - 如何在 Vue.js 中上传图片之前显示图片?

php - 上传图片并在 codeigniter 中插入文本

mysql - 为什么将子查询从 FROM 移动到 SELECT 会导致 NULL?

codeigniter - 从另一个模型加载和使用 codeigniter 模型

php - Controller 之间的 codeigniter $this->load->vars

asp.net-mvc - 从本地系统上传图片 + TinyMCE 编辑器 + ASP.NET MVC

mysql - 尝试在 MySQL 中连接 3 个表

php - sql avg 使用导致结果集的非法排序

mysql - sql 子查询返回 "Every derived table must have its own alias"

php - Codeigniter MySQL 连接复杂