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

l0oc07j2  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(326)

这是广泛讨论的问题topic:how to 上传时是否在数据库中保存图像url?
我已经读过了,但仍然不明白为什么我的控制器不工作。我遵循了codeigniters文档中关于上传文件的内容,并创建了一个将文件上传到所需目录中的控件,目前为止还不错。我现在想保存上传时在数据库中的图像网址。我修改了这个问题的代码,但我有多个错误,我不能绕过。
1.
消息:非法字符串偏移量“file\u name”
文件名:controllers/upload.php
行号:36
2.message:未定义属性:upload::$db
文件名:controllers/upload.php
行号:37
3.message:在null上调用成员函数insert()
文件名:controllers/upload.php
行号:37
这是我的控制器(我的测试表puzz有两个字段-自动递增主键id和图像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);
                }
        }
}
?>

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

lymgl2op

lymgl2op1#

在使用insert之前添加此项

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

相关问题