Search code examples
codeigniterforeign-keysdefault-value

Uploading images with foreign key constraint


I have a foreign key constraint in an images table which is the user_id column in my users table. When I try to upload a new image, I get the DB error

1364: Field 'user_id' doesn't have a default value.

I suspect it’s because the code is looking for a value to add to the images column. I originally thought that if the session is set, loading an image would automatically identify the user who’s uploading the image.

Question: How can I include data that would merge the two tables when a user uploads an image? Here is the code in the controller that uploads the image:

function upload() {
        //$filename = md5(uniqid(rand(), false));
        $config = array(
            'upload_path' => 'uploads',
            'allowed_types' => "gif|jpg|png|jpeg",
            //'file_name' => $filename,
            'max_size' => 200,
            'max_width' => 1024,
            'max_height' => 768     
        );          


    $this->load->library('upload', $config);

    if(empty($this->session->userdata['email'])){
               redirect(site_url().'/main/login/');

        }else       
    $this->load->library('upload', $config);

    if($this->upload->do_upload())
        {
        $file_data = $this->upload->data();

        $data['name'] = $file_data['file_name'];
        $data['file'] = $file_data['file_path'];
        $data['file_type'] = $file_data['file_type'];
        $data['file_size'] = $file_data['file_size'];           
        $data['date_uploaded'] = date('Y/m/d H:i:s');

The images_model:

function save_image($data){     
    $this->db->insert('images', $data);
} 

The 'images' table:

Appreciate ALL input and suggestions.


Solution

  • I think in your application only users can upload image ... Then before uploading image you should check if user is signed or not and get user id ...

    when you want to add new record to images table you must add user_id to $data array

    $data['user_id'] = $this->session->userdata('user_id'); // or anything you added to session

    .....