尝试使用按钮将图像上传到CodeIgniter中的数据库但我收到错误

时间:2017-06-08 14:16:12

标签: php codeigniter image-uploading

我试图在CodeIgniter(PHP)中创建一个函数,以便用户可以将图像添加到我的数据库中,但是当我尝试上传图像时出现错误..图片确实在我的上传文件夹,但它不会上传到我的phpmyadmin表格行。

我正在使用phpMyAdmin

数据库名称:kadokado

表名:产品

表格行名称我想将这些图像放到:product_foto

图片文件夹:上传

我的控制器文件(Product.php):

    class Product extends CI_Controller { 


    var $data = array();

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

}

     public function index()
 {
  $config = array (
   'upload_path' => 'upload/',
   'allowed_types' => 'jpg|jpeg|png|bmp',
   'max_size' => 0,
   'filename' => url_title($this->input->post('file'))

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

   if ($this->upload->do_upload('file')) {
    $this->db->insert('products', array(
        'product_foto' => $this->upload->product_foto
     ));
     $this->session->set_flashdata('msg', 'Success');
   }

  $this->load->view('product_form', $this->data);
 }

}

这是我的视图文件(product_form.php):

<?php
echo $this->session->flashdata('msg');
echo form_open_multipart();
echo form_upload('file');
echo form_submit('upload', 'Upload');
echo form_close();
?>

这些是我得到的错误:`

  A PHP Error was encountered

Severity: Notice

Message: Undefined property: CI_Upload::$product_foto

Filename: controllers/Product.php

Line Number: 21

Backtrace:

File: /home/ubuntu/workspace/application/controllers/Product.php
Line: 21
Function: _error_handler

File: /home/ubuntu/workspace/index.php
Line: 315
Function: require_once






A Database Error Occurred

Error Number: 1048

Column 'product_foto' cannot be null

INSERT INTO `products` (`product_foto`) VALUES (NULL)

Filename: controllers/Product.php

Line Number: 22

1 个答案:

答案 0 :(得分:0)

尝试此功能

public function index() {
  $data = array();

  $config = array(
      'upload_path' => 'upload',
      'allowed_types' => 'jpg|jpeg|png|bmp',
      'max_size' => 250,
      'max_width' => 1920,
      'max_heigh' => 1080,
  );
 $this->load->library('upload', $config);

 if (!$this->upload->do_upload('userfile')) {

   $error = array('error' => $this->upload->display_errors());
   // var_dump( $error); die; check errors 
 } else {
   $fileName = $this->upload->data();
   $data['product_foto'] = $fileName['file_name'];
   $this->db->insert('products', $data);
   $this->session->set_flashdata('msg', 'Success');
 }
   $this->load->view('product_form');
}