Welcome Guest, Not a member yet? Register   Sign In
Insert uploaded filenames into specific SQL columns
#1

[eluser]invision[/eluser]
Hi,

The code I've posted below works great.

It allows me to upload images and generate 2 thumbnails from them. These images are moved to my 'uploads' directory and the filenames all added to a 'photos' sql table.

However, instead of inserting the filename data into a 'photos' SQL table, I wonder if I can insert them in a sequence along with the rest of my form data (into the 'entries' table).
Part of my 'entries' table has the following structure:
img1 | img1sml | img2 | img2sml | img3 | img3sml | img4 | img4sml | img5 | img5sml | img6 | img6sml
and I'd ultimately like to move all 12 images (total) into these columns listed above.


Can anyone assist where I would begin with this? Would I have to pass this data to my addAccommodationEntry method?



Many thanks for any guidance.



Here's my Controller code for moving the Images and Form Data:
Code:
function create(){
       if ($this->input->post('ptitle')){
          $file_name = !empty($data['upload_data']) ? $data['upload_data']['file_name'] : NULL ;
          $config['upload_path'] = './uploads/';
      $config['allowed_types'] = 'gif|jpg|png';
      $config['max_size']    = '2048'; //2 meg
      $config['encrypt_name']    = TRUE;
      $this->load->library('upload', $config);
      $this->load->library('image_lib');
      //Upload error flag
      $error = FALSE;
          
          foreach($_FILES as $key => $value)
      {
          if( !empty($value['name']))
          {
              if ( $this->upload->do_upload($key) )
              {
                  $uploaded = $this->upload->data();

                  //Create Thumbnail
                  $config['image_library'] = 'GD2';
                  $config['source_image'] = $uploaded['full_path'];
                  $config['create_thumb'] = TRUE;
                  $config['thumb_marker'] = '_tn';
                  $config['master_dim'] = 'width';
                  $config['quality'] = 75;
                  $config['maintain_ratio'] = TRUE;
                  $config['width'] = 240;
                  $config['height'] = 160;

                  $this->image_lib->clear();
                  $this->image_lib->initialize($config);
                  $this->image_lib->resize();

                  //Create Thumbnail 2
                  $config['image_library'] = 'GD2';
                  $config['source_image'] = $uploaded['full_path'];
                  $config['create_thumb'] = TRUE;
                  $config['thumb_marker'] = '_tn2';
                  $config['master_dim'] = 'width';
                  $config['quality'] = 100;
                  $config['maintain_ratio'] = TRUE;
                  $config['width'] = 93;
                  $config['height'] = 75;

                  $this->image_lib->clear();
                  $this->image_lib->initialize($config);
                  $this->image_lib->resize();

                  //$imagename = $uploaded['file_name'].'_tn'.$uploaded['file_ext'];
                  $imagename = substr($uploaded['file_name'], 0, -4)."_tn".$uploaded['file_ext'];  
                  $timestamp = now();

                  //Add Pic Info To Database
                  $this->db->set('file', $imagename);
                  $this->db->set('date', $timestamp);
                  $this->db->set('entry_id', 21);
                  //$this->db->set('thumb_type', $config['thumb_marker']);
                  //$this->db->set('img_id', $i);

                  //Insert Info Into Database
                  $this->db->insert('photos');
              }
              else
              {
                  $error = TRUE;
              }
          }
      }
          
      $this->MEntries->addAccommodationEntry($file_name);
          $this->session->set_flashdata('message','Entry created');
          redirect('admin/entries/index','refresh');
          
        } else {
          $data['title'] = "Create Entry";
          $data['main'] = 'admin_entries_create';
          $this->load->vars($data);
          $this->load->view('dashboard');    
      }
  }

For the record, here's a snippet of my 'MEntries' Model:

Code:
$data = array(            
            'title' => $this->input->post('ptitle'),
            'user_id' => $_SESSION['userid'],
            'pubdate' => $now,
            'img' => $file_name
        );    
        $this->db->insert('entries', $data);
#2

[eluser]invision[/eluser]
I really hate to bump, but could anyone take a look over this and assist?

I'm confident it's probably pretty straightforward and I'm missing something obvious.


Many thanks for any help.
#3

[eluser]n0xie[/eluser]
Maybe I'm not understanding the question correctly but reading your code, if you already know the entry_id, why not update the entries record when you upload the pictures?
Code:
#Your code:
    //Add Pic Info To Database
    $this->db->set('file', $imagename);
    $this->db->set('date', $timestamp);
    $this->db->set('entry_id', 21); # <-- you know the entry_id

    //Insert Info Into Database
    // $this->db->insert('photos'); # <-- instead of photo's we take entries


#Example code not tested:
    $this->db->set('img1', $imagename)
            ->set('img1sml', str_replace('_tn','_tn2', $imagename))
            ->where('entry_id', (int) $entry_id)
            ->update('entries');
You probably need to test your if img1 to img6 is NOT NULL beforehand to make sure you don't overwrite them.

Or alternatively, just make 1 VARCHAR/BLOB/MEMO field where you store a JSON object that hold all your images related to that entry. When retrieving, convert them to an array, and just add new images to the end of the array, convert back to JSON and overwrite the old object.
#4

[eluser]invision[/eluser]
Hi N0xie

Many thanks for taking a look.

Apologies, I've actually hardcoded the entry_id in above example.
Code:
$this->db->set('entry_id', 21); // hard coded for testing purposes
If I'm moving the filename data into the 'entries' table I won't need to have the entry_id.


Is there a simple way to move this data into my entries columns?


Best result for me (if possible) would be to move the filename data straight to my 'addAccommodationEntry' method:

Code:
$data = array(            
            'title' => $this->input->post('ptitle'),
            'user_id' => $_SESSION['userid'],
            'pubdate' => $now,
            'img1' => $file_name[img1],
            'img1sml' => $file_name[img1sml],
            etc....
        );
$this->db->insert('entries', $data);

Is this possible?


Thanks again sir
#5

[eluser]n0xie[/eluser]
This implies that you upload the images at the same time you are creating the entry. Is this correct?

If so you could do something like that:
Code:
# pseudo code
class Entries extends CI_Controller

    function create()
    {
        // all your form validation crap here
        // if they pass:
        
        $images = $this->_handle_upload();
    
        // do damage control here if something went wrong with the file upload
        if ( ! $images) show_404('something went wrong during upload');
    
        $data = array_merge($data, $images);
        
        $this->entries_model->save($data);
    }
    
    function _handle_upload()
    {
        // put all your upload code here (basically c/p your create() function)
        
        // inside your foreach loop
        
        // instead of inserting we do:
        $fieldname = 'img' . $i;
        $fieldname_small = 'img' . $i . 'sml';
        $image[$fieldname]    =  $imagename;
        $image[$fieldname_small] = str_replace('_tn','_tn2', $imagename);
        
        $i++;
        
        // end foreach loop
        
        return ($error) ? FALSE : $image;
        
    }

Obviously you could move the upload stuff to a different library/module/model instead of doing it in the controller.
#6

[eluser]invision[/eluser]
Quote:This implies that you upload the images at the same time you are creating the entry. Is this correct?
Bingo!

I'll take a look at this code right and see how I go Smile


Thanks again for the help with this. Wish me luck.
#7

[eluser]invision[/eluser]
Hey.

I've tried using the code (I uploaded 2 images with my 'entry'), but it didn't seem to move the file name data into the columns in my entries table. Just moved them into the photos table.

For the record, here's my current 'Entries' Controller:

Code:
function _handle_upload()
    {
        // put all your upload code here (basically c/p your create() function)
        $file_name = !empty($data['upload_data']) ? $data['upload_data']['file_name'] : NULL ;
            $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '2048'; //2 meg
        $config['encrypt_name']    = TRUE;
        $this->load->library('upload', $config);
        $this->load->library('image_lib');
        //Upload error flag
        $error = FALSE;
            
            foreach($_FILES as $key => $value)
        {
            if( !empty($value['name']))
            {
                if ( $this->upload->do_upload($key) )
                {
                    $uploaded = $this->upload->data();
  
                    //Create Thumbnail
                    $config['image_library'] = 'GD2';
                    $config['source_image'] = $uploaded['full_path'];
                    $config['create_thumb'] = TRUE;
                    $config['thumb_marker'] = '_tn';
                    $config['master_dim'] = 'width';
                    $config['quality'] = 75;
                    $config['maintain_ratio'] = TRUE;
                    $config['width'] = 240;
                    $config['height'] = 160;
  
                    $this->image_lib->clear();
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
  
                    //Create Thumbnail 2
                    $config['image_library'] = 'GD2';
                    $config['source_image'] = $uploaded['full_path'];
                    $config['create_thumb'] = TRUE;
                    $config['thumb_marker'] = '_tn2';
                    $config['master_dim'] = 'width';
                    $config['quality'] = 100;
                    $config['maintain_ratio'] = TRUE;
                    $config['width'] = 93;
                    $config['height'] = 75;
  
                    $this->image_lib->clear();
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
  
                    //$imagename = $uploaded['file_name'].'_tn'.$uploaded['file_ext'];
                    $imagename = substr($uploaded['file_name'], 0, -4)."_tn".$uploaded['file_ext'];  
                    $timestamp = now();
  
                    //Add Pic Info To Database
                    $this->db->set('file', $imagename);
                    $this->db->set('date', $timestamp);
                    $this->db->set('entry_id', 21);
                    //$this->db->set('thumb_type', $config['thumb_marker']);
                    //$this->db->set('img_id', $i);
  
                    //Insert Info Into Database
                    $this->db->insert('photos');
                }
                else
                {
                    $error = TRUE;
                }
            }
        }
      
        // instead of inserting we do:
        $image['image']    =  $imagename;
        $image['image_small'] = str_replace('_tn','_tn2', $imagename);
        
        return ($error) ? FALSE : $image;
        
    }
  
  function create(){
  
      // all your form validation crap here
       if ($this->input->post('ptitle')){
        
        // if they pass:        
        $images = $this->_handle_upload();
    
        // do damage control here if something went wrong with the file upload
        if (!$images) show_404('something went wrong during upload');
        
        $this->MEntries->addAccommodationEntry();
            $this->session->set_flashdata('message','Entry created');
            redirect('admin/entries/index','refresh');
          
        } else {
          $data['title'] = "Create Entry";
          $data['main'] = 'admin_entries_create';
          $this->load->vars($data);
          $this->load->view('dashboard');    
      }
  }
#8

[eluser]n0xie[/eluser]
Take a look at my updates code.

A couple of pointers:
- You need to put the $image array inside your foreach loop in your _handle_upload() function
- The updated code should take care of several uploaded pictures
- You need to pass the $data to your addAccomodationEntry model
#9

[eluser]invision[/eluser]
Many thanks for your persistence with this.

I've updated the code and now get the following errors on upload:

Quote:A PHP Error was encountered
Severity: Notice
Message: Undefined variable: i
Filename: admin/entries.php
Line Number: 95

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: i
Filename: admin/entries.php
Line Number: 96

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: i
Filename: admin/entries.php
Line Number: 100

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: admin/entries.php
Line Number: 117

A PHP Error was encountered
Severity: Warning
Message: array_merge() [function.array-merge]: Argument #1 is not an array
Filename: admin/entries.php
Line Number: 117

A Database Error Occurred
Error Number: 1054
Unknown column 'file' in 'field list'
INSERT INTO `entry` (`file`, `date`, `entry_id`, `atitle`, `aslug`, `status`, `body`, `metakeys`, `metadescr`, `address`, `cost`, `city`, `country`, `addressdescr`, `features`, `roomclass1`, `gmap`, `agent`, `category`, `category_id`, `atype`, `user_id`, `pubdate`) VALUES ('e244452d6785818ab4174408623caa52_tn.jpg', 1296215545, 21, 'Bla bla', 'bla-bla', 'published', 'Bla bla', 'Bla bla', 'Bla bla', 'Bla bla', 'Bla bla', '1', '1', 'Bla bla', 'Bla bla', 'Bla bla', '', '1', 0, '6', '1', '1', '2011-01-28 11:52:25')

I think we're getting there.

Should I be splitting my array so I can move the different images into their respective columns?







For reference, here's my current code:

Code:
function _handle_upload()
    {
        // put all your upload code here (basically c/p your create() function)
        $file_name = !empty($data['upload_data']) ? $data['upload_data']['file_name'] : NULL ;
            $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size']    = '2048'; //2 meg
        $config['encrypt_name']    = TRUE;
        $this->load->library('upload', $config);
        $this->load->library('image_lib');
        //Upload error flag
        $error = FALSE;
            
            foreach($_FILES as $key => $value)
        {
            if( !empty($value['name']))
            {
                if ( $this->upload->do_upload($key) )
                {
                    $uploaded = $this->upload->data();
  
                    //Create Thumbnail
                    $config['image_library'] = 'GD2';
                    $config['source_image'] = $uploaded['full_path'];
                    $config['create_thumb'] = TRUE;
                    $config['thumb_marker'] = '_tn';
                    $config['master_dim'] = 'width';
                    $config['quality'] = 75;
                    $config['maintain_ratio'] = TRUE;
                    $config['width'] = 240;
                    $config['height'] = 160;
  
                    $this->image_lib->clear();
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
  
                    //Create Thumbnail 2
                    $config['image_library'] = 'GD2';
                    $config['source_image'] = $uploaded['full_path'];
                    $config['create_thumb'] = TRUE;
                    $config['thumb_marker'] = '_tn2';
                    $config['master_dim'] = 'width';
                    $config['quality'] = 100;
                    $config['maintain_ratio'] = TRUE;
                    $config['width'] = 93;
                    $config['height'] = 75;
  
                    $this->image_lib->clear();
                    $this->image_lib->initialize($config);
                    $this->image_lib->resize();
  
                    //$imagename = $uploaded['file_name'].'_tn'.$uploaded['file_ext'];
                    $imagename = substr($uploaded['file_name'], 0, -4)."_tn".$uploaded['file_ext'];  
                    $timestamp = now();
  
                    //Add Pic Info To Database
                    $this->db->set('file', $imagename);
                    $this->db->set('date', $timestamp);
                    $this->db->set('entry_id', 21);
                    //$this->db->set('thumb_type', $config['thumb_marker']);
                    //$this->db->set('img_id', $i);
  
                    //Insert Info Into Database
                    //$this->db->insert('photos');
                }
                else
                {
                    $error = TRUE;
                }
            }
        }
      
        // instead of inserting we do:        
        $fieldname = 'img' . $i;
        $fieldname_small = 'img' . $i . 'sml';
        $image[$fieldname]    =  $imagename;
        $image[$fieldname_small] = str_replace('_tn','_tn2', $imagename);
        
        $i++;
        
        return ($error) ? FALSE : $image;
        
    }
  
  function create(){
  
      // all your form validation crap here
       if ($this->input->post('ptitle')){
        
        // if they pass:        
        $images = $this->_handle_upload();
    
        // do damage control here if something went wrong with the file upload
        if (!$images) show_404('something went wrong during upload');
        
        $data = array_merge($data, $images);
        
        $this->MEntries->addAccommodationEntry($data);
            $this->session->set_flashdata('message','Entry created');
            redirect('admin/entries/index','refresh');
          
        } else {
          $data['title'] = "Create Entry";
          $data['main'] = 'admin_entries_create';
          $this->load->vars($data);
          $this->load->view('dashboard');    
      }
  }
#10

[eluser]invision[/eluser]
Should I be looking to modify this line to allow for all the different images(img1 | img1sml | img2 | img2sml | img3 | img3sml | img4 | img4sml | img5 | img5sml | img6 | img6sml)

Code:
//Add Pic Info To Database
$this->db->set('file', $imagename);

?




Theme © iAndrew 2016 - Forum software by © MyBB