CodeIgniter - Uploading an Image through a form, store the location of the image in database

30,880

CodeIgniter's file uploading class will do this for you. The entry in their user guide explains as well as I could, so I'm going to point you there.

Essentially you'd just need to modify the controller that they have there to include a bit where you put the file URL in the database, which you can accomplish easily by using $this->upload->data() and extracting [full_path] from the resulting array, and then sending it to a model which handles the database input.

Share:
30,880
scrot
Author by

scrot

Updated on July 09, 2022

Comments

  • scrot
    scrot almost 2 years

    I'm trying to upload an image to my site through a form, however it's much more efficient to (rather than bog down the database) just store the location of the image in the database.

    I'm having trouble with my form and really don't know where to go:

    <?=form_open('bro/submit_new');?>
     //other form data
     Image: <input type="file" name="image" size="20" /> <br>
     <input type="submit" value="Submit" />
    </form>
    

    Now the form itself works fine, the problem is that it's trying to store the image into the database field 'image' (which is type TEXT). What's the easiest way to tell it to just store the file, and give the file location to store in the 'image' field? (I tell it where to upload the file via the controller).

    Thanks

    Edit: controller code (for this part):

    function submit_new(){
        $config['upload_path'] = './images/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '2000';
        $config['max_width']  = '1024';
        $config['max_height']  = '768';     
        $this->load->library('upload', $config);
    
        $this->db->insert('post', $_POST);
    
        redirect('bro');
    }
    
  • scrot
    scrot over 15 years
    I was under the impression that it loaded the file directly into the database? Do I have that wrong?
  • scrot
    scrot over 15 years
    But I guess I didn't think as to why it would load it to both locations
  • victoriah
    victoriah over 15 years
    No, it uploads it to whatever directory you specify :) Read the user guide! Hehe. Not idiotic at all. The user guide is a bit vast for everyone to know everything there is to know about CodeIgniter.