我正在尝试在codeigniter中的同一个mysql表中上传图像和文本,但我收到的数据库错误如“你必须使用”set“方法来更新条目。”
控制器上的代码
class Addnews extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
}
function index()
{
$this->load->view('addnews', array('error' => ' ' ));
}
function do_upload()
{
$config['upload_path'] = './assets/images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';
$config['max_width'] = '1040';
$config['max_height'] = '1040';
$this->load->library('upload', $config);
$this->upload->initialize($config);
$newRow = array("news_title" => $this->input->post('news_title'),
"news_description" => $this->input->post('news_description'));
$data = array('upload' => $this->upload->data());
$result = array_merge($newRow, $data);
if ( ! $this->upload->do_upload())
{
$image_data = $this->upload->data();
$newRow['imgpath'] ='assets/images/'.$image_data['file_name'];
$this->load->view('addnews');
}
else
{
$this->load->model("modeladdnews");
$this->modeladdnews->insert_news($result);
$this->load->view('success');
}
}
}
?>
模型上的代码
<?php
class Modeladdnews extends CI_Model {
function insert_news($result)
{
$this->db->insert('news');
}
}
?>
视图上的代码
<html>
<head>
<title>Upload Form</title>
</head>
<body>
<?php echo form_open_multipart('Addnews/do_upload');?>
<?php
echo form_input("news_title", "");
echo form_input("news_description", "");
echo form_upload("userfile");
?>
<br /><br />
<input type="submit" value="submit" />
</form>
</body>
</html>
答案 0 :(得分:0)
CI活动记录类插入方法接受两个参数1st是table_name,第二个是不在insert函数中发送数据的数组,看它应该是这样的。
class Modeladdnews extends CI_Model {
function insert_news($result)
{
$this->db->insert('news',$result);
}
}
答案 1 :(得分:0)
你的概念是错误的:上传文件是一回事,更新数据库是另一回事!图像上传后(到服务器上的目录),您将要在数据库中保存图像路径和其他图像数据(如日期,描述等)或执行一些图像处理。
您应该将do_upload控制器组织如下:
if ( ! $this->upload->do_upload())
{
//error
$error = $this->upload->display_errors();
$this->load->view('upload_form', $error);
}
else
{
// success!!, file was uploaded
// get data for this file;
$data = array('upload_data' => $this->upload->data());
$img = $data['upload_data']['file_name'];
$data['other_stuff']=$_POST;
// Now update the database
$this->modeladdnews->insert_news($data);
}
答案 2 :(得分:0)
$config['upload_path'] = './uploads/images';
$config['allowed_types'] = 'gif|jpg|png|JPG|PNG|GIF';
$config['max_size'] = '20000';
$config['max_width'] = '102400';
$config['max_height'] = '76800';
$this->load->library('upload', $config);
if (!$this->upload->do_upload('userfile')) {
echo "Error While uploading image ! please go back and try again";
} else {
$upload_data = $this->upload->data();
$data['image'] = $upload_data['file_name'];
$data['caption'] = $_POST['caption'];
$this->db->insert('tbl_name', $data); }