简体   繁体   中英

Code Igniter - How to save images into database

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)

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/

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); 
            }
        }

}

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']));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM