Code Igniter - How to Save Images to Database

I am using codeIgniter to upload files to folders on the server. Now I also want to store the data in the database, what do I need to get the raw data and then store it in the database?

Here's the model for saving files:

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


This is how I call it from the boot controller:

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

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


Table structure:

  • file_data (LONG BLOB)
  • filename (VARCHAR)

source to share

3 answers

I solved the problem using the convenient 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']));




Keeping track is the best method. But if you want to try ....

This is the same as in PHP or CodeIgniter,

I'd rather give you a link and then write the code here:



Try it, it works 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){
                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); 





All Articles