Registration form with image upload in Codeigniter

13,849

This is how I handle file uploads with form... it's a generic example but it should help.

View

<?php echo form_open_multipart('someController/someFunction') ?>

    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name">
    </div>

    <div class="form-group">
        <label for="uploads">Upload a file</label>
        <input name="uploads[]" id="fileupload" type="file" multiple="true">
    </div>

    <input type="submit">

<?php echo form_close() ?>

Controller

public function addRecordToTable()
{
    $this->form_validation->set_rules('name' , 'Name', 'required');

    if ($this->form_validation->run() == true) {
        $array = array(
            'name'      => $this->input->post('name')
        );

        $record_id = $this->some_model->addData('some_table', $array);
        $this->uploadFiles($record_id);
    }
}

public function uploadFiles($record_id)
{
    $config = array(
        'upload_path'   => FCPATH . "path\to\directory",
        'allowed_types' => 'jpg|png|jpeg',
        'overwrite'     => TRUE,                       
    );

    $this->load->library('upload', $config);

    $files = $_FILES['uploads'];

    foreach ($files['name'] as $key => $filename) {
        $_FILES['uploads[]']['name']     = $files['name'][$key];
        $_FILES['uploads[]']['type']     = $files['type'][$key];
        $_FILES['uploads[]']['tmp_name'] = $files['tmp_name'][$key];
        $_FILES['uploads[]']['error']    = $files['error'][$key];
        $_FILES['uploads[]']['size']     = $files['size'][$key];

        $config['file_name'] = $filename;

        $this->upload->initialize($config);

        if (isset($_FILES['uploads[]']['name']) && !empty($_FILES['uploads[]']['name'])) {
            if ( ! $this->upload->do_upload('uploads[]')) {
                $error = array('error' => $this->upload->display_errors());

            } else {
                $uploads[] = $this->upload->data();
                $array = array(
                    'record_id' => $record_id,
                    'filename'  => $_FILES['uploads[]']['name'],
                    'size'      => $_FILES['uploads[]']['size']
                );
                $this->some_model->addData('uploads', $array);
            }
        }
    }
    redirect(base_url() . 'someController/someFunction/' . $record_id);
}

Model

public function addData($table, $array)
{
    $this->db->insert($table, $array);

    return $this->db->insert_id();
}

Edit:

As per your comment, to insert data into multiple tables, simply modify the code in your controller so:

public function submitEmployeeDetails()
{
    $this->form_validation->set_rules('value1' , 'Value 1', 'required');
    $this->form_validation->set_rules('value2' , 'Value 2', 'required');

    if ($this->form_validation->run() == true) {
        $array1 = array(
            'value1' => $this->input->post('value1')
        );

        $array2 = array(
            'value2' => $this->input->post('value2')
        );           

        $this->your_model->addData('employees', $array1);
        $this->your_model->addData('employees_details', $array2);
    }
}

So you have two arrays and you call the addData() function in the model, the first parameter specifies the name of the table and the second passes the associative array to be added.

Share:
13,849

Related videos on Youtube

Pretorian
Author by

Pretorian

Updated on June 04, 2022

Comments

  • Pretorian
    Pretorian almost 2 years

    I have a user registration form and it's working fine but would like to add an image upload feature inside it. This is basically what I'd like to achieve

    ScreenShot 1Screenshot 1

    ScreenShot 2screenshot 2

    So far, this is what I have done

    Controller:

    class Employees extends CI_Controller {
    var $pgToLoad;
    
    public function __construct() {
        parent::__construct();
        #this will start the session
        session_start();
        $this->load->helper(array('form', 'url'));
    
    
        if(!isset($_SESSION['userId']) || !isset($_SESSION['userLevel']) || !isset($_SESSION['employeeid']) || !isset($_SESSION['firstname']) || !isset($_SESSION['lastname'])) {
            redirect('home', 'location');
        }
    
        #this will load the model
        $this->load->model('Contents');
    
        #get last uri segment to determine which content to load
        $continue = true;
        $i = 0;
        do {
            $i++;
            if ($this->uri->segment($i) != "") $this->pgToLoad = $this->uri->segment($i);
            else $continue = false;             
        } while ($continue);        
    }
    
    public function index() {       
        $this->main();
    }   
    
    public function main() {
        #set default content to load 
        $this->pgToLoad = empty($this->pgToLoad) ? "employees" : $this->pgToLoad;
        $disMsg = "";
    
        #this will delete the record selected
        if($this->uri->segment(2) == 'delete') { 
            $this->deleteRecord();
        }
    
        #this will check if the post value is trigger
        if(isset($_POST['addnew'])) {
            $this->addRecord(); 
        }                   
    
        #this will check if the post value is trigger
        if(isset($_POST['saveinfo'])) {
            $this->updateinfo();    
        }           
    
        if($this->uri->segment(2) == 'add' || $this->uri->segment(2) == 'edit') {
            #this display the form for products
            $this->displayForm();
        } else {
            #this will display the job orders
            $this->getAllEmployees();       
        }   
    
    
        if($this->uri->segment(2) == 'print') {
            #this display the form for products
            $this->pdf();
        } 
    
    if($this->uri->segment(2) == 'do_upload') {
            #this display the form for products
            $this->do_upload();
        } 
    
        #this will logout the user and redirect to the page
        if($this->uri->segment(2) == 'logout') {
            session_destroy();
            redirect('home', 'location');
        }                   
    
        $data = array ( 'pageTitle' => 'Payroll System | ADMINISTRATION',
                        'disMsg'    => $disMsg,                                             
                        'mainCont'  => $this->mainCont );
    
        $this->load->view('mainTpl', $data, FALSE);
    }
    
    
    function do_upload(){
    
        if($this->input->post('upload')){
    
            $config['upload_path'] = './uploads/';
            $config['allowed_types'] = 'gif|jpg|png';
            $config['max_size']    = '1024';
            $config['max_width']  = '1024';
            $config['max_height']  = '768';
            $this->load->library('upload', $config);
    
            if ( ! $this->upload->do_upload()){
    
            $error = array('error' => $this->upload->display_errors());
            $this->load->view('pages/employeesform', $error);
            }
    
            else{
    
            $data=$this->upload->data();
            $this->thumb($data);
            $file=array(
            'img_name'=>$data['raw_name'],
            'thumb_name'=>$data['raw_name'].'_thumb',
            'ext'=>$data['file_ext'],
            'upload_date'=>time()
            );
            $this->Contents->add_image($file);
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('pages/upload_success', $data);
            }
        }
    
        else{
    
        redirect(site_url('employees'));
    
        }
    
    }
    
    function thumb($data){
    
        $config['image_library'] = 'gd2';
        $config['source_image'] =$data['full_path'];
        $config['create_thumb'] = TRUE;
        $config['maintain_ratio'] = TRUE;
        $config['width'] = 275;
        $config['height'] = 250;
        $this->load->library('image_lib', $config);
        $this->image_lib->resize();
    
    }
        public function displayForm() {
        $data['level'] = $this->Contents->exeGetUserLevel();
        $data['status'] = $this->Contents->exeGetUserStatus();
    
        $data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);      
        if($this->uri->segment(2) == 'edit') { 
            $data['employee'] = $this->Contents->exeGetEmpToEdit($_SESSION['userId']);
            $data['emp'] = $this->Contents->exeGetEmpToEdit($this->uri->segment(3));
            $data['info'] = $this->Contents->exeGetUserInfo($this->uri->segment(3));    
            $this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);
        }                   
        $this->mainCont = $this->load->view('pages/employeesform', $data, TRUE);                
    }
    
    #this will add new record
    public function addRecord() {
        if(empty($_POST['fname']) || empty($_POST['mname']) || empty($_POST['lname']) || empty($_POST['empass']) || empty($_POST['emailadd']) || empty($_POST['gender']) || empty($_POST['datehired']) || empty($_POST['salary'])) {    
            $disMsg = "Please fill up the form completely.";
            $_SESSION['disMsg'] = $disMsg;  
        } else {
            $addNew = $this->Contents->exeAddNewRecord();
    
            if($addNew['affRows'] > 0) {
                $_SESSION['disMsg'] = "New Employee has been added.";
                redirect('employees', 'location');          
            } else {
                $disMsg = "Unable to add new employee.";
            }       
        }           
    }
    

    Views:

     <?php echo form_open_multipart('employees/do_upload');?>
    
                <img id="preview" style = "width: 200px; height: 200px;">
                <input type="file" name = "userfile" id="input">
    
                <br /><br />
    
                <input type="submit" value="upload" name="upload" />
    
                </form>
    
    
    <form action="" method="post" enctype="multipart/form-data" id="empform" role="form" name="empform">
                <div class="box-body">
                    <div class="row">
                        <div class="col-lg-6">
                            <div class="input-field col s12">
                                <label>Firstname</label>
                                <input type="text" id="fname" name="fname" class="form-control" value="<?php if(!empty($_POST['fname'])) { echo $_POST['fname']; } elseif(!empty($emp[0]['firstname'])) { echo $emp[0]['firstname']; } ?>">
                            </div>
                            <div class="input-field col s12">
                                <label>Middle Name</label>
                                <input type="text" id="mname" name="mname" class="form-control" value="<?php if(!empty($_POST['mname'])) { echo $_POST['mname']; } elseif(!empty($emp[0]['middlename'])) { echo $emp[0]['middlename']; } ?>">
                            </div>
                            <div class="input-field col s12">
                                <label>Password</label>
                                <input type="password" id="empass" name="empass" class="form-control" value="<?php if(!empty($_POST['empass'])) { echo $_POST['empass']; } ?>">
                            </div>
                            <div class="input-field col s12">
                                <label>Employee ID</label>
                                <input type="text" id="empno" name="empno" class="form-control" value="<?php if(!empty($_POST['empno'])) { echo $_POST['empno']; } elseif(!empty($emp[0]['employeeid'])) { echo $emp[0]['employeeid']; } ?>">
                            </div>
                        </div>
                            <div class="col-lg-4" style="padding-left:0;">
                                <?php if($this->uri->segment(2) == "edit") { ?>
                                <button type="submit" name="saveinfo" class="btn btn-lg btn-primary btn-block">Save</button>
                                <?php } else { ?>
                                <button type="submit" name="addnew" class="btn btn-lg btn-primary btn-block">Save</button>
                                <?php } ?>
    
                            </div>
                        </div>
                    </div>
                </form>
    

    As you can see in views, there are 2 forms. First form is for image upload and the other one is user registration form. How will I be able to include the image upload in the reg form and perform image upload, save user info and form validation once save button is clicked?

  • Pretorian
    Pretorian about 8 years
    What if I have multiple tables?
  • DinosaurHunter
    DinosaurHunter about 8 years
    You can call the public function addData($table, $array) function and pass whatever you want for the parameters. Both functions I've used in the controller use this method - but for different tables.
  • Pretorian
    Pretorian about 8 years
    Wait I have 2 tables, employees and employee_details wherein I will store form field values. How will I pass that tables to addData() function?
  • Pretorian
    Pretorian about 8 years
    thanks. So I wiil remove the parameter of uploadFiles($record_id)?
  • DinosaurHunter
    DinosaurHunter about 8 years
    Not necessarily - because that is what calls the function to upload your files
  • Pretorian
    Pretorian about 8 years
    So meaning I can assign the two statements into $record_id and call the function uploadFiles() twice?
  • DinosaurHunter
    DinosaurHunter about 8 years
    If you wanted to upload the files twice, sure.