这是一个被广泛讨论的主题:如何在上传时将图像URL保存在数据库中?
我已阅读过但仍无法理解我的控制器无法正常工作的原因。我跟着CodeIgniters documentation on uploading files创建了控制器,将文件上传到所需的目录中,到目前为止一切顺利。我现在想在上传时将图像URL保存在数据库中。我修改了this question的代码但我有多个错误,我无法解决。
1
消息:非法字符串偏移' file_name'
文件名:controllers / Upload.php
行号:36
2.Message:未定义的属性:Upload :: $ db
文件名:controllers / Upload.php
行号:37
3.Message:在null
上调用成员函数insert()文件名:controllers / Upload.php
行号:37
这是我的控制器(我有两个字段的测试表puzz - 自动增加主键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);
}
}
}
?>
如果有人能在我的代码中指出错误,我们将不胜感激!
答案 0 :(得分:1)
在使用insert
之前添加它$this->load->database();
OR
更改构造函数
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->database();
}
autoload.php OR
更改
$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);