更新图像的PHP更改为默认值

时间:2018-05-11 06:37:48

标签: php image-uploading crud

我们正在开发自己的MVC框架并在编辑时如果我们不更改图像,则图像更改为默认值。除非重新选择图像,否则我们不希望图像在编辑模式下更改。

我们的代码如下:

HTML(查看)

<form id="form-category" class="form-horizontal" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">

<div class="form-group">
    <label class="col-sm-2 control-label">Image</label>
    <div class="col-sm-10">
        <a href="" id="thumb-image" data-toggle="image" class="img-thumbnail">
            <img src="<?php echo HTTP_HOST ?>/image/<?php echo $data['industry_image']; ?>" alt="<?php echo $data['industry_name']; ?>" title="<?php echo $data['industry_name']; ?>"  data-placeholder="<?php echo HTTP_HOST ?>/image/<?php echo $data['placeholder']; ?>" width="100" height="100">
            <input type="hidden" name="delete_image" value="<?php echo $data['industry_image']; ?>">
        </a>
        <input type="file" class="hidden" name="industry_image" value="<?php echo $data['industry_image']; ?>" id="input-image" onchange="readURL(this);">
    </div>
</div>

</form>

jQuery for displaying image on file select
function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#thumb-image').children('img').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }

jQuery for Bootstrap Popover

$(document).on('click', 'a[data-toggle=\'image\']', function(e) {
    var $element = $(this);
    var $popover = $element.data('bs.popover'); // element has bs popover?

    e.preventDefault();

    // destroy all image popovers
    $('a[data-toggle="image"]').popover('destroy');

    // remove flickering (do not re-add popover when clicking for removal)
    if ($popover) {
        return;
    }

    $element.popover({
        html: true,
        placement: 'right',
        trigger: 'manual',
        content: function() {
            return '<button type="button" id="button-image" class="btn btn-primary"><i class="fa fa-pencil"></i></button> <button type="button" id="button-clear" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>';
        }
    });

    $element.popover('show');

    $('#button-image').on('click', function() {
        $('#input-image').trigger('click');

        // $element.parent().find('input').attr('value', '');

        $element.popover('destroy');
    });

    $('#button-clear').on('click', function() {
        $element.find('img').attr('src', $element.find('img').attr('data-placeholder'));

        $element.parent().find('input').attr('value', '');
        //alert($('#input-image').attr('value', ''));

        $element.popover('destroy');
    });
});

控制器

$data = [
'industry_image' => isset($_POST['industry_image'] ? $_POST['industry_image'] : NULL
]

if(empty($_FILES['industry_image']['size'])) {
    $data['industry_image'] = 'no-image.png';
} else {
            $file = $_FILES['industry_image'];

            $fileName = $file['name'];
            $fileTmpName = $file['tmp_name'];
            $fileSize = $file['size'];
            $fileError = $file['error'];
            $fileType = $file['type'];

            $fileExt = explode('.', $fileName);
            $fileActualExt = strtolower(end($fileExt));

            $allowed = array('gif', 'jpg', 'jpeg', 'png');
            $allowedFileSize = 2000000;

            if(in_array($fileActualExt, $allowed)) {
                if($fileError === 0) {
                    if($fileSize < $allowedFileSize) {
                        $fileNameNew = strtolower($data['industry_name']) . "." . $fileActualExt;
                        $fileDestination = DIR_IMAGE . 'industries/' . $fileNameNew;
                        $filePath = 'industries/' . $fileNameNew;

                        if(array_key_exists('delete_image', array($data['industry_image']))) {
                            if(file_exists($filePath)) {
                                unlink($filePath);
                            }
                        }

                        $moveResult = move_uploaded_file($fileTmpName, $fileDestination);

                        if($moveResult != true) {
                            echo "Error: File Upload Failed. Try again.";
                            unlink($fileTmpName);
                            exit;
                        } else {
                            if(file_exists($fileNameNew)) {
                                flash("file_alert alert-danger", "File already exists");
                            } else {
                                $data['industry_image'] = $filePath;
                            }
                        }
                    } else {
                        flash("file_alert alert-danger", "File size is $fileSize of $allowedFileSize");
                    }
                } else {
                    flash("file_alert alert-danger", "Error uploading the file");
                }
            } else {
                $a = "Please upload only ";
                foreach($allowed as $ext) {
                    $a .= '<b>' . $ext . '</b>' . ', ';
                }
                $a .= " extensions";

                flash("file_alert alert-danger", $a);
            }
        }

if($this->model->getIndustries($industry_id, $data) {
    redirect("catalog/industries", $data);
} else {
    redirect("catalog/industries_form", $data);
}

模型

public function editIndustry($industry_id, $data) {
    # Prepare Query for category
    $this->db->query("UPDATE industry SET industry_name = :industry_name, industry_description = :industry_description, sort_order = :sort_order, status = :status WHERE industry_id = '" . $industry_id ."'");

    # Bind Values
    $this->db->bind(':industry_name', $data['industry_name']);
    $this->db->bind(':industry_description', $data['industry_description']);
    $this->db->bind(':sort_order', $data['sort_order']);
    $this->db->bind(':status', $data['status']);

    # Execute
    $this->db->execute();

    if(isset($data['industry_image'])) {
        $this->db->query("UPDATE industry SET industry_image = :image WHERE industry_id = '" . $industry_id . "'");
        $this->db->bind(":image", $data['industry_image']);
        //$this->db->execute();
    }

    # Execute
    if($this->db->execute()) {
        return $industry_id;
    } else {
        return false;
    }
}

Bootstrap popover image

Edit Image

上面的代码有效,但如前所述,即使我们没有在POST上选择,图像也会更新。如果图像未经编辑,则应将相同的图像转到数据库。如果我们使用红色删除按钮清除数据库,则输入标记中的值应清除,应将 no-image.png 发送到数据库。

希望,我能解释一下我的问题,并寻找一个解决方案,你们真棒的人。

谢谢。

0 个答案:

没有答案