0

I am new to CI.Can anyone help me giving tutorial for image uploading for CI 2.0. I have make an folder Product_image in asset folder.My table name is tbl_product.my controller page is product and code is:

<?php 
include_once('application/backend/controllers/dashboard.php');

 class Product extends Dashboard {
    function _construct(){
        parent::_construct();
        $this->load->model('product_model');
}

 public function index() {

   $this->islogin();
   $data=$this->generateCommonItems();
   $this->load->model('product_model');
   $data['page_title']="List of Products";
   $data['page_heading']="List of Products";
   $data['listAllProduct']=$this->product_model->listAllProduct();
   $this->load->view('products/listproduct',$data);
}

function addproduct() {
    $this->data['title'] = 'Add Product';

    //validate form input
    $this->form_validation->set_rules('prod_name', 'Product name',     'required|xss_clean');
    $this->form_validation->set_rules('prod_des', 'Description', 'required|xss_clean');
    $this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
    $this->form_validation->set_rules('prod_image', 'Picture', 'required|xss_clean');

    if ($this->form_validation->run() == true)
    {       
        $data = array(
            'prod_name'             => $this->input->post('prod_name'),
            'prod_des'      => $this->input->post('prod_des'),
            'price'             => $this->input->post('price'),
            'prod_image'            => $this->input->post('prod_image')
        );

        $this->product_model->insert_product($data);
        redirect('product/addproduct');

    } else {
        $data=$this->generateCommonItems();
        //display the add product form
        //set the flash data error message if there is one

        $this->data['prod_name'] = array(
            'name'      => 'name',
            'id'        => 'name',
            'type'      => 'text',
            'style'     => 'width:300px;',
            'value'     => $this->form_validation->set_value('name'),
        );          
        $this->data['prod_des'] = array(
            'name'      => 'description',
            'id'        => 'description',
            'type'      => 'text',
            'cols'      =>  60,
            'rows'      =>  5,
            'value'     => $this->form_validation->set_value('description'),
        );
        $this->data['price'] = array(
            'name'      => 'price',
            'id'        => 'price',
            'type'      => 'text',
            'style'     => 'width:40px;text-align: right',
            'value'     => $this->form_validation->set_value('price'),
        );
        $this->data['prod_image'] = array(
            'value' => $this->form_validation->set_value('prod_image'),
        );

        $this->load->view('includes/header',$data);
        $this->load->view('products/product_form', $this->data);
                    $this->load->view('includes/footer',$data);
    }
}

 public function delete($prod_id) {

   $this->islogin();
   $this->load->model('product_model');
    if($this->product_model->deleteByid($prod_id))
        redirect('product/index');
}

function edit_product($prod_id) {
    $product = $this->product_model->get_product($prod_id);

    $this->data['title'] = 'Edit Product';

    //validate form input
    $this->form_validation->set_rules('prod_name', 'Product name', 'required|xss_clean');$this->form_validation->set_rules('description', 'Description', 'required|xss_clean');
    $this->form_validation->set_rules('price', 'Price', 'required|xss_clean');
    $this->form_validation->set_rules('prod_image', 'Picture', 'required|xss_clean');

    if (isset($_POST) && !empty($_POST))
    {       
        $data = array(
            'prod_name'                 => $this->input->post('prod_name'),
            'prod_des'          => $this->input->post('prod_des'),
            'price'                 => $this->input->post('price'),
            'prod_image'                => $this->input->post('prod_image'),
        );

        if ($this->form_validation->run() === true)
        {
            $this->product_model->update_product($prod_id, $data);          
            redirect(base_url().'product/edit/'.$prod_id);
        }           
    }       
    $this->data['tbl_product'] = $product;

    //display the edit product form
    $this->data['prod_name'] = array(
        'name'      => 'name',
        'id'        => 'name',
        'type'      => 'text',
        'style'     => 'width:300px;',
        'value'     => $this->form_validation->set_value('name', $product['name']),
    );

    $this->data['prod_des'] = array(
        'name'      => 'description',
        'id'        => 'description',
        'type'      => 'text',
        'cols'      =>  60,
        'rows'      =>  5,
        'value'     => $this->form_validation->set_value('description', $product['description']),
    );

    $this->data['price'] = array(
        'name'      => 'price',
        'id'        => 'price',
        'type'      => 'text',
        'style'     => 'width:40px;text-align: right',
        'value'     => $this->form_validation->set_value('price', $product['price']),
    );

    $this->data['prod_image'] = array(
        'name'  => 'picture',
        'id'    => 'picture',
        'type'  => 'text',
        'style' => 'width:250px;',
        'value' => $this->form_validation->set_value('prod_image', $product['picture']),
    );

    $this->load->view('products/edit_product', $this->data);
}

}

my model page is product_model:

<?php class Product_model extends CI_Model {

 function __construct() {

     parent::__construct();
}

function listAllProduct() {
    $query = $this->db->select('*')->from('tbl_product')->get();
    //return $query = result();
    //$query = $this->db->query("select * from tbl_product");
    return $query->result();    
}

function get_product($prod_id) {
    $this->db->select('prod_id, prod_name, prod_des, price, prod_image');
    $this->db->where('prod_id', $prod_id);
    $query = $this->db->get('tbl_product');

    return $query->row_array();
}

public function insert_product($data) {
    if ($this->db->insert('tbl_product', $data))
        return true;
    else {
        return false;
    }
}

public function update_product($prod_id, $data) {
    $this->db->where('prod_id', $prod_id);
    $this->db->update('tbl_product', $data);
}

function deleteByid($prod_id) {
    $this->db->where('prod_id', $prod_id);
    if ($this->db->delete('tbl_product')) {
        return true;
    } else {
        return false;
    }

View:

    <h2 align="center">Add Product</h2>
     <?php echo form_open("product/addproduct");?>
     <table width="700" border="1" cellpadding="0" cellspacing="2" align="center">
        <tr>
            <td width="130" align="right" bgcolor="#FFFFFF">Product Name: </td>
            <td><?php echo form_input($prod_name);?></td>
        </tr>
        <tr>
            <td width="130" align="right" bgcolor="#FFFFFF">Product Description: </td>
            <td><?php echo form_textarea($prod_des); ?></td>
        </tr>
        <tr>
            <td align="right" bgcolor="#FFFFFF">Price:</td>
            <td><?php echo form_input($price); ?></td>
        </tr>
        <tr>
            <td align="right" bgcolor="#FFFFFF">Picture:</td>
            <td><?php echo form_input($prod_image); ?></td>
        </tr>
        <tr>
            <td align="right" bgcolor="#FFFFFF">&nbsp;</td>
            <td><?php echo form_submit('submit', 'Submit');?>
        </tr>
    </table>
<?php echo form_close(); ?>

Form page view:

      <h2 align="center">Add Product</h2>
      <?php echo form_open("product/addproduct");?>
      <table width="700" border="1" cellpadding="0" cellspacing="2" align="center">
        <tr>
            <td width="130" align="right" bgcolor="#FFFFFF">Product Name: </td>
            <td><?php echo form_input($prod_name);?></td>
        </tr>
        <tr>
            <td width="130" align="right" bgcolor="#FFFFFF">Product Description: </td>
            <td><?php echo form_textarea($prod_des); ?></td>
        </tr>
        <tr>
            <td align="right" bgcolor="#FFFFFF">Price:</td>
            <td><?php echo form_input($price); ?></td>
        </tr>
        <tr>
            <td align="right" bgcolor="#FFFFFF">Picture:</td>
            <td><?php echo form_input($prod_image); ?></td>
        </tr>
        <tr>
            <td align="right" bgcolor="#FFFFFF">&nbsp;</td>
            <td><?php echo form_submit('submit', 'Submit');?>
        </tr>
    </table>
<?php echo form_close(); ?>

I m thankful to him/her who give me solution for this error code by checking mistake n error?

2 Answers 2

1

1: You have to use the attribute open_multipart when uploading files in forms:

<?php echo form_open_multipart('product/addproduct');?>

2: Take off the file form attrribute from the form validation: Delete this:

$this->form_validation->set_rules('prod_image', 'Picture', 'required|xss_clean');

3: Use this to save the file in folder:

$config['upload_path'] = './asset/Product_image/'; //The path where the image will be save
$config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
$config['max_size'] = '2048'; //The max size of the image in kb's
$config['max_width']  = '1024'; //The max of the images width in px
$config['max_height']  = '768'; //The max of the images height in px
$config['overwrite'] = TRUE; //If exists an image with the same name it will overwrite. Set to false if don't want to overwrite
$this->load->library('upload', $config); //Load the upload CI library
if (!$this->upload->do_upload('userfile')){
    $uploadError = array('upload_error' => $this->upload->display_errors()); 
    $this->set_flashdata('uploadError', $uploadError, $urlYouWantToReturn); //If for some reason the    upload could not be done, returns the error in a flashdata and redirect to the page you specify in $urlYouWantToReturn
    exit;
}

4: After that, you gonna grab the file name to save the file reference in Database. Put right below:

$file_info = $this->upload->data('userfile');
$file_name = $file_info['file_name']; //Now you got the file name in the $file_name var. Use it to record in db.
//You can assign it to your data array to pass to your update_product function.

5: Now, the whole code merged:

function addproduct() {
$this->data['title'] = 'Add Product';

//validate form input
$this->form_validation->set_rules('prod_name', 'Product name',     'required|xss_clean');
$this->form_validation->set_rules('prod_des', 'Description', 'required|xss_clean');
$this->form_validation->set_rules('price', 'Price', 'required|xss_clean');

if ($this->form_validation->run() == true)
{
    $config['upload_path'] = './asset/Product_image/'; //The path where the image will be save
    $config['allowed_types'] = 'gif|jpg|png'; //Images extensions accepted
    $config['max_size']    = '2048'; //The max size of the image in kb's
    $config['max_width']  = '1024'; //The max of the images width in px
    $config['max_height']  = '768'; //The max of the images height in px
    $config['overwrite'] = TRUE; //If exists an image with the same name it will overwrite. Set to  false if don't want to overwrite
    $this->load->library('upload', $config); //Load the upload CI library
    if (!$this->upload->do_upload('userfile')){
        $uploadError = array('upload_error' => $this->upload->display_errors()); 
        $this->set_flashdata('uploadError', $uploadError, $urlYouWantToReturn); //If for some reason the upload could not be done, returns the error in a flashdata and redirect to the page you specify in $urlYouWantToReturn
       exit;
    }
    $file_info = $this->upload->data('userfile');
    $file_name = $file_info['file_name']; //Now you got the file name in the $file_name var. Use it to record in db.
    $data = array(
        'prod_name' => $this->input->post('prod_name'),
        'prod_des'  => $this->input->post('prod_des'),
        'price'     => $this->input->post('price'),
        'prod_image'=> $file_name,
    );

    $this->product_model->insert_product($data);
    redirect('product/addproduct');

} else {
    $data=$this->generateCommonItems();
    //display the add product form
    //set the flash data error message if there is one

    $this->data['prod_name'] = array(
        'name'      => 'name',
        'id'        => 'name',
        'type'      => 'text',
        'style'     => 'width:300px;',
        'value'     => $this->form_validation->set_value('name'),
    );          
    $this->data['prod_des'] = array(
        'name'      => 'description',
        'id'        => 'description',
        'type'      => 'text',
        'cols'      =>  60,
        'rows'      =>  5,
        'value'     => $this->form_validation->set_value('description'),
    );
    $this->data['price'] = array(
        'name'      => 'price',
        'id'        => 'price',
        'type'      => 'text',
        'style'     => 'width:40px;text-align: right',
        'value'     => $this->form_validation->set_value('price'),
    );
    $this->data['prod_image'] = array(
        'value' => $this->form_validation->set_value('prod_image'),
    );

    $this->load->view('includes/header',$data);
    $this->load->view('products/product_form', $this->data);
    $this->load->view('includes/footer',$data);
}

}

This is what i use in my CI projects, hope it helps!

Sign up to request clarification or add additional context in comments.

1 Comment

@ArthurMastropietro - can you look out this stackoverflow.com/questions/34431199/… question?
0

You can upload images with form by giving it an attribute of enctype.

<?php echo form_open_multipart('product/addproduct');?>
      <input type="file" name="userfile" size="20" />
      <input type="submit" value="Submit">
<?php echo form_close();?>

CodeIgniter also have some helper classes that can be found in the documentation. Here's one:

http://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.