简体   繁体   中英

Image is not uploaded in database in codeigniter

I have created a small form in codeigniter. All fields are inserted properly into database, where as the file field(photo) is neither uploaded nor inserted into database.

Here is my model, view, controller files.

****My View files****(form1.php)

<?php 
    $this -> load -> file("assets/fckeditor/fckeditor.php", true);
    $fck_base_path=$this->config->base_url().'assets/fckeditor/';
?>

<div class="white_back">
 <div class="white_back_1">q</div>
 <div class="white_back_2">
   <div class="white_back_2_title">Application Forms</div><br>
   <div class="clear">&nbsp;</div>
   <div class="form_container">
    <!--<form method="post" id="reg_form"  name="reg_form" action="emp_reg.php">-->
                <?php echo form_open_multipart('form1'); ?>
                    <fieldset>
                    <legend>General Information</legend>
                    <dl>
                        <dt>
                            <label for="candidate_name"> <span class="req">*</span>Candidate's Name:</label>
                        </dt>
                        <dd>
                            <input type="text" name="candidate_name" id="candidate_name"  value="<?php echo set_value('candidate_name'); ?>"/><?php echo form_error('candidate_name'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="father_name"> <span class="req">*</span>Father's Name:</label>
                        </dt>
                        <dd>
                            <input type="text" name="father_name" id="father_name"  value="<?php echo set_value('father_name'); ?>"/><?php echo form_error('father_name'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="mother_name"> <span class="req">*</span>Mother's Name:</label>
                        </dt>
                        <dd>
                            <input type="text"  id="mother_name" name="mother_name"  value="<?php echo set_value('mother_name'); ?>"/><?php echo form_error('mother_name'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="local_guardian"> Local guardian:</label>
                        </dt>
                        <dd>
                            <input type="text"  id="local_guardian" name="local_guardian"  value="<?php echo set_value('local_guardian'); ?>"/>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="gender"> <span class="req">*</span><?php echo form_label('Gender: ', 'gender'); ?></label>
                        </dt>
                        <dd>
                             <?php echo form_label('Female', 'female'). form_radio('gender', 'F', NULL, 'id="female" '.set_radio('gender', 'F'));?> 
                             <?php echo form_label('Male', 'male'). form_radio('gender', 'M', NULL, 'id="male" '.set_radio('gender', 'M'));?> 
                             <?php echo form_error('gender'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="gender"> <span class="req">*</span><?php echo form_label('Category: ', 'category'); ?></label>
                        </dt>
                        <dd>
                                <?php echo form_label('OBC', 'OBC'). form_radio('category', 'OBC', NULL, 'id="OBC" '.set_radio('category', 'OBC'));?>
                                <?php echo form_label('SC', 'SC'). form_radio('category', 'SC', NULL, 'id="SC" '.set_radio('category', 'SC'));?>
                                <?php echo form_label('ST', 'ST'). form_radio('category', 'ST', NULL, 'id="ST" '.set_radio('category', 'ST'));?>
                                <?php echo form_label('GEN', 'GEN').form_radio('category', 'GEN', NULL, 'id="GEN" '.set_radio('category', 'GEN'));?>
                                <?php echo form_error('category'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="dob"> <span class="req">*</span>Date of birth</label>
                        </dt>
                      <dd>
                              <?php
                              $myCalendar = new tc_calendar("date5", true, false);
                              $myCalendar->setIcon($this->config->base_url()."/calendar/images/iconCalendar.gif");
                              //$myCalendar->setDate(date('d'), date('m'), date('Y'));
                              $myCalendar->setPath($this->config->base_url()."/calendar/");
                              $myCalendar->setYearInterval(2000, 2020);
                              $myCalendar->dateAllow('2008-05-13', '2015-03-01');
                              $myCalendar->setDateFormat('j F Y');
                              //$myCalendar->setHeight(350);
                              //$myCalendar->autoSubmit(true, "form1");
                              $myCalendar->setAlignment('left', 'bottom');
                              $myCalendar->setSpecificDate(array("2011-04-01", "2011-04-04", "2011-12-25"), 0, 'year');
                              $myCalendar->setSpecificDate(array("2011-04-10", "2011-04-14"), 0, 'month');
                              $myCalendar->setSpecificDate(array("2011-06-01"), 0, '');
                              $myCalendar->writeScript();
                              ?><?php echo form_error('date5'); ?>
                      </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="gender"> Photo</label>
                        </dt>
                        <dd>
                            <input type="file"  id="photo" name="photo" value="<?php echo set_value('photo'); ?>"><?php echo form_error('photo'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="gender">Interested for:</label>
                        </dt>
                        <dd>
                            <input type="checkbox" name="mycheck[]" value="reading" <?php echo set_checkbox('mycheck', 'reading'); ?> />
                            <label class="opt">reading</label>
                            <input type="checkbox" name="mycheck[]" value="singing" <?php echo set_checkbox('mycheck', 'singing'); ?> />
                            <label class="opt">singing</label>
                            <input type="checkbox" name="mycheck[]" value="dancing" <?php echo set_checkbox('mycheck', 'dancing'); ?> />
                            <label class="opt">dancing</label>
                            <input type="checkbox" name="mycheck[]" value="none" <?php echo set_checkbox('mycheck', 'none'); ?> />
                            <label class="opt">None of these</label>
                            <?php echo form_error('mycheck'); ?>
                        </dd>
                    </dl>
                    </fieldset>
                    <div class="clear1"></div>
                    <fieldset>
                    <legend>Contact Information</legend>
                    <dl>
                        <dt>
                            <label for="street_address1"> <span class="req">*</span>Email</label>
                        </dt>
                        <dd>
                            <input type="text"  name="email" id="email"  value="<?php echo set_value('email'); ?>"/><?php echo form_error('email'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="street_address2">Phone no</label>
                        </dt>
                        <dd>
                            <input type="text" name="phone_no" id="phone_no"  value="<?php echo set_value('phone_no'); ?>"/>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="street_address3">Mobile no</label>
                        </dt>
                        <dd>
                            <input type="text"  name="mobile_no" id="mobile_no"  value="<?php echo set_value('mobile_no'); ?>"/>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="city"> <span class="req">*</span>Mailing Address</label>
                        </dt>
                        <dd>
                            <?php                        
                            $oFCKeditor = new FCKeditor('mailing_address') ;
                            $oFCKeditor->BasePath = $fck_base_path ;
                            $oFCKeditor->Value = set_value('mailing_address');
                            $oFCKeditor->Create() ;
                           ?><?php echo form_error('mailing_address'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="city"> <span class="req">*</span>City</label>
                        </dt>
                        <dd>
                            <input type="text"  name="city" id="city"  value="<?php echo set_value('city'); ?>"/><?php echo form_error('city'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="state"> <span class="req">*</span>State</label>
                        </dt>
                        <dd>
                           <input type="text"  name="state" id="state"  value="<?php echo set_value('state'); ?>"/><?php echo form_error('state'); ?>
                        </dd>
                    </dl>
                    <dl>
                        <dt>
                            <label for="country"> <span class="req">*</span>Country</label>
                        </dt>
                        <dd>
                                <?php
                                $query = $this->db->query('SELECT country_id, country_name  FROM country order by country_name asc');
                                $options = array(); 
                                $options[0]='Please select country';
                                        foreach ($query->result() as $row)
                                        {
                                          //$all= $row->country_id  .'=>'. $row->country_name.',';
                                          $options[$row->country_id]=$row->country_name;
                                        }
                                        //print_r($options);
                                 $selected = ($this->input->post('country')) ? $this->input->post('country') : $this->input->post('country');                                 echo form_dropdown('country', $options, $selected);
                                ?><?php echo form_error('country'); ?>
                     </dd>
                    </dl>
                    <dl>
                        <dt> </dt>
                        <dd>
                            <input type="submit"  value="Submit" />
                            <input type="reset" name="reg_reset" id="reg_reset" value="Reset" />
                        </dd>
                    </dl>
                    </fieldset>
                </form>
    </div>
 </div>
</div>


--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

My controller (form1.php)

<?php
class Form1 extends CI_Controller {

    public function __construct()
    {
        parent::__construct();
        $this->load->model('form1_model');
    }

    function index()
    {   
        $this->load->helper(array('form', 'url'));
         //$this->load->helper('form');
        $this->load->library('form_validation');
        $this->load->view('templates/header');
        //$this->load->helper(array('form1', 'url'));


        $this->form_validation->set_error_delimiters('<div class="error">', '</div>');

        $this->load->database();

        $this->form_validation->set_rules('candidate_name', 'Candidate name', 'required');
        //$this->form_validation->set_rules('username', 'Username', 'required|callback_username_check');
        $this->form_validation->set_rules('father_name', 'Father name', 'required');
        $this->form_validation->set_rules('mother_name', 'Mother name', 'required');
        $this->form_validation->set_rules('gender', 'Gender', 'required');
        $this->form_validation->set_rules('category', 'Category', 'required');
        $this->form_validation->set_rules('date5', 'Date of birth', 'required|callback_dob_check');
        //$this->form_validation->set_rules('photo', 'Photo', 'required|callback_photo_check');
        $this->form_validation->set_rules('mycheck', 'Newsletter', 'required');
        $this->form_validation->set_rules('email', 'Email', 'required|valid_email|is_unique[school_registration.email]');
        $this->form_validation->set_rules('mailing_address', 'Mailing address', 'required');
        $this->form_validation->set_rules('city', 'City', 'required');
        $this->form_validation->set_rules('state', 'State', 'required');
        $this->form_validation->set_rules('country', 'Country', 'required|callback_country_check');
        $this->form_validation->set_rules('photo', 'Photo', 'callback_do_upload');




        if ($this->form_validation->run() == FALSE)
        {
            $this->load->view('form1');
        }
        else
        {   
            $this->form1_model->insert_records();
            $this->load->view('formsuccess');
        }

        $this->load->view('templates/footer');
    }

    public function dob_check($str)
    {
       if($str == '0000-00-00')
       {
          $this->form_validation->set_message('dob_check', 'Please select your date  of birth');
          return FALSE;
       }
    }

   public function photo_check($str)
    {
      if (empty($_FILES['photo']['name']))
        {
           $this->form_validation->set_rules('photo', 'Photo', 'required');
        }
    }




    public function country_check($str)
    {
       if($str == '0')
       {
          $this->form_validation->set_message('country_check', 'Please select your country');
          return FALSE;
       }
    }



    public function username_check($str)
    {
        if ($str == 'test')
        {
            $this->form_validation->set_message('username_check', 'The %s field can not be the word "test"');
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }


    function do_upload()
    {
        $config['upload_path'] = './uploads/';
        $config['allowed_types'] = 'gif|jpg|png';
        $config['max_size'] = '100';
        $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('upload_form', $error);
            $this->form_validation->set_message('do_upload', $error);
        }
        else
        {
            $data = array('upload_data' => $this->upload->data());
            $this->load->view('upload_success', $data);
        }
    }

}
?>



----------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------

my model(form1_model)

<?php
class Form1_model extends CI_Model {

    public function __construct()
    {
        $this->load->database();
    }

    public function insert_records()
   {

//      $upload_data = $this->upload->data();
//      print_r($upload_data);
//      //echo $upload_data['photo'];
        //print_r($this->input->post('mycheck'));
        $temp=$this->upload->data();
        var_dump($temp);
        $image=$temp['file_name'];// to get image file name rom upload script , as it could be stored in the databae

        $hobbies_implode=implode(",",$this->input->post('mycheck'));
        $data = array(
        'candidate_name' => $this->input->post('candidate_name'),
        'father_name' => $this->input->post('father_name'),
        'mother_name' => $this->input->post('mother_name'),
        'local_guardian' => $this->input->post('local_guardian'),
        'gender' => $this->input->post('gender'),
        'category' => $this->input->post('category'),
        'dob' => $this->input->post('date5'),
        'email' => $this->input->post('email'),
        'phone_no' => $this->input->post('phone_no'),
        'mobile_no' => $this->input->post('mobile_no'),
        'mailing_address' => $this->input->post('mailing_address'),
        'city' => $this->input->post('city'),
        'state' => $this->input->post('state'),
        'photo' => $image,
        'hobbies' => $hobbies_implode,
        'country' => $this->input->post('country')
        );
        return $this->db->insert('school_registration', $data);
   }
}

I don't see any code for saving the file. You upload a file to temporary folder which disappears when script is ended. Your script is ended before you start saving anything to db.

Here's a short sample code:

if (!empty($_FILES)) {
    $tempFile = $_FILES['Filedata']['tmp_name'];
    $targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder . $_FILES['Filedata']['name'];
        move_uploaded_file($tempFile,$targetFile);
}

You need that move_uploaded_file() function to save it.

On the other note, I wouldn't run queries in your view file. You have a model for that. That's the whole point of MVC and codeigniter.

you need to pass the input type file control name as an argument in the do_upload() function. by default it is 'userfile'.

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