上传时在数据库中存储图像 url 时出现问题 (CodeIgniter)

Problems storing image url in database on upload (CodeIgniter)

这已被广泛讨论 topic:how 要在上传时将图像 url 保存到数据库中吗?

我已经阅读了它们,但仍然无法理解为什么我的控制器无法正常工作。我关注了 CodeIgniters documentation on uploading files and created controler that uploads file in desired directory, so far so good. I now want to save image url in database on upload. I modified code from this question,但我遇到了多个无法解决的错误。

1.

Message: Illegal string offset 'file_name'

Filename: controllers/Upload.php

Line Number: 36

2.Message: Undefined property: Upload::$db

Filename: controllers/Upload.php

Line Number: 37

3.Message: Call to a member function insert() on null

Filename: controllers/Upload.php

Line Number: 37

这是我的控制器(我用两个字段测试 table 拼图 - 自动递增主键 ID 和 image_url):

<?php

class Upload extends CI_Controller {

        public function __construct()
        {
                parent::__construct();
                $this->load->helper(array('form', 'url'));
        }

        public function index()
        {
                $this->load->view('upload_form', array('error' => ' ' ));
        }

        public function do_upload()
        {
                $config['upload_path']          = './uploads/';
                $config['allowed_types']        = 'gif|jpg|png';
                $config['max_size']             = 100;
                $config['max_width']            = 1024;
                $config['max_height']           = 768;

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

                if ( ! $this->upload->do_upload('userfile'))
                {
                        $error = array('error' => $this->upload->display_errors());

                        $this->load->view('upload_form', $error);
                }
                else
                {
                        $data = $this->upload->data();
                        $file_array = $this->upload->data('file_name');
                        $image['image_url'] = $file_array['file_name'];
                        $this->db->insert('puzz', $image);
                        $this->load->view('upload_success', $data);
                }
        }
}
?>

如果有人能指出我的代码中的错误,我将不胜感激!

在使用插入之前添加这个

$this->load->database();

OR 更改构造函数

public function __construct()
    {
            parent::__construct();
            $this->load->helper(array('form', 'url'));
            $this->load->database();
}

OR 变化 autoload.php

$autoload['libraries'] = array('database');

AND 将此代码块更改为

$data = $this->upload->data();
$image['image_url'] = $data['file_name'];
$this->db->insert('puzz', $image);
$this->load->view('upload_success', $data);