我在哪里放插入数据库查询codeigniter

时间:2014-09-16 07:03:47

标签: php codeigniter

在我的控制器中,我有以下功能将图像上传到本地目录,该目录工作正常。我现在想存储在db中。我只需要弄清楚我已经拥有的代码放在哪里,并认为是正确的。

我需要插入此内容:

  $this->location->store_file_path($file);

在pic上传到本地目录之前或之后。它应该去哪里?

控制器:

public function image() {

    //type must either be type=logo or type=profile_picture

    if (isset($_FILES['file']) && isset($_POST['type'])) {

        //Codeigniter upload
        $config['upload_path'] = 'uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['encrypt_name'] = TRUE;
        $config['max_size'] = 5120;
        $config['max_width'] = '1024';
        $config['max_height'] = '768';
        $this->upload->initialize($config);

        if (!$this->upload->do_upload('file')) {

            $status = 'error';
            $msg = $this->upload->display_errors('', '');
        } else {
            $data = $this->upload->data();
             //$file_id = $this->files_model->insert_file($data['file_name'], $_POST['title']);
            if ($data) {
                $status = "success";
                $data['url'] = $config['upload_path'] . $data['file_name'];
                $msg = $data;
            } else {
                unlink($data['full_path']);
                $status = "error";
                $msg = "Something went wrong when saving the file, please try again.";
            }


        }
    } else {
        $status = "error";
        $msg = "Please select a file to upload";
    }
    echo json_encode(array('status' => $status, 'msg' => $msg));
}

这是我的模型功能:

public function store_file_path($file)
{

    $this->db->insert('TACTIFY_locationcards', 'name'=>$file);
}

2 个答案:

答案 0 :(得分:0)

我建议您在完成所有验证并将数据写入文件后才写入数据库。

如果我正确地阅读了您的代码,那么成功就在于:

           if ($data) {
            $status = "success";
            $data['url'] = $config['upload_path'] . $data['file_name'];
            $msg = $data;

我会把这句话放在这里:

           if ($data) {
            $status = "success";
            $data['url'] = $config['upload_path'] . $data['file_name'];
            $msg = $data;
            $this->location->store_file_path($file);

答案 1 :(得分:0)

更改控制器中的以下行

$status = "success";
 + $file = $config['upload_path'] . $data['file_name'];
 + $this->location->store_file_path($file);
 $msg = $file;

更改模型

public function store_file_path($file)
{
   + $this->db->set('name', $file); 
   + $this->db->insert('TACTIFY_locationcards'); 
   - $this->db->insert('TACTIFY_locationcards', 'name'=>$file);
}