【问题标题】:Problems storing image url in database on upload (CodeIgniter)上传时在数据库中存储图像 url 的问题 (CodeIgniter)
【发布时间】:2017-02-15 00:06:54
【问题描述】:

这是一个被广泛讨论的话题:如何在上传时将图片网址保存在数据库中?

我已阅读它们,但仍然无法理解为什么我的控制器不工作。我关注CodeIgniters documentation on uploading files 并创建了将文件上传到所需目录的控制器,到目前为止一切顺利。我现在想在上传时将图像 url 保存在数据库中。我从this question 修改了代码,但我有多个无法解决的错误。

1.

消息:非法字符串偏移 'file_name'

文件名:控制器/Upload.php

行号:36

2.Message:未定义的属性:Upload::$db

文件名:控制器/Upload.php

行号:37

3.Message:在 null 上调用成员函数 insert()

文件名:控制器/Upload.php

行号:37

这是我的控制器(我有两个字段的测试表难题 - 自动递增主键 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);
                }
        }
}
?>

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

【问题讨论】:

    标签: mysql codeigniter file-upload image-uploading


    【解决方案1】:

    在使用插入之前添加这个

    $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);
    

    【讨论】:

      猜你喜欢
      • 2016-09-06
      • 2011-02-16
      • 2011-03-30
      • 2015-04-15
      • 1970-01-01
      • 2011-06-21
      • 2010-09-22
      • 2022-01-14
      • 2012-01-30
      相关资源
      最近更新 更多