3

I'm making use of codeIgniter to upload files into folders in the server. Now I also want to save the data into the database, what do I need in order to get the raw data and then save it into the database?

Here's the model for saving files:

<?php
class files extends ci_Model{
    function saves($filename, $filedata, $post_id){
        $this->db->query("INSERT INTO tbl_files SET file_data='$filedata', filename='$filename', postid='$post_id'");
    }
}
?>

Here's how I call it from the upload controller:

$filename = $data['upload_data']['file_name'];
$file_data = file_get_contents($data['upload_data']['file_name']);

$this->load->model('files');
$this->files->saves($filename, $file_data, 'ID1');

Table Structure:

  • file_data (LONG BLOB)
  • filename (VARCHAR)
Wern Ancheta
  • 22,397
  • 38
  • 100
  • 139
  • 2
    Why don't you just save the path to the image, not the image itself? The performance will be better. Look at http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – Rooneyl Mar 16 '12 at 12:49
  • They say it's more secure when you store it on the database plus it's also portable, you won't have to worry about the filesystem structure when you change from one operating system to another – Wern Ancheta Mar 16 '12 at 12:54
  • I wouldn't because something can easily go wrong when save it to the database. To aid security you could always save the images above the htdocs folder – Rooneyl Mar 16 '12 at 13:31

3 Answers3

2

Storing Path is very best method. But if you want to try ....

It is same as in PHP or CodeIgniter ,

Better I give you the link, then writing code here: http://www.techcubetalk.com/2009/01/tutorial-on-how-to-store-images-in-mysql-blob-field/

gustavohenke
  • 40,997
  • 14
  • 121
  • 129
TechCare99
  • 1,763
  • 6
  • 24
  • 33
1

Try it , it's work on my code`

function _save($id = null){

    $config['upload_path'] = './asset/';
    $config['allowed_types'] = 'gif|jpg|png|jpeg';
    $config['max_size'] = '1000';
    $config['max_width'] = '1024';
    $config['max_height'] = '768';
    $config['encrypt_name'] = TRUE;
    $this->load->library('upload', $config);    

        if($_POST || $_FILES){
            if(!$this->upload->do_upload('field_input_name')){
                echo $this->upload->display_errors('<p>', '</p>');
            } else {
                $w = $this->upload->data();
                $data = array(
                    'field_input_name' => $w['file_name'],
                    );
                 $this->db->insert('table_image', $data); 
            }
        }

}

jned29
  • 477
  • 12
  • 50
0

I have solved the problem by using the handy mysql_real_escape_string() like this:

$filename = $data['upload_data']['file_name'];
$file_data = mysql_real_escape_string(file_get_contents($data['upload_data']['full_path']));
Wern Ancheta
  • 22,397
  • 38
  • 100
  • 139