我需要上传一个带有它名字的图像,并更改为表格(列)

table

My table(posts){id, title, post, date_added, userID, active, urlfile}

Here I want to upload with my this controller and model with view a file where it must inter that file name to the urlfile and upload it to the (/uploads/). My controller work fine if I insert only text and delete upload section but it's not working

Controller Code:

function new_post() {

        $data['errors'] = 0;
        if ($_POST) {

            $config = array( array('field' => 'title', 'rules' => 'trim|requird'), array('field' => 'post', 'rules' => 'trim|required'));
            $this -> load -> library('form_validation');
            $this -> form_validation -> set_rules($config);
            if ($this -> form_validation -> run() == false) {
                $data['errors'] = validation_errors();
            }
            $data = array('title' => $_POST['title'], 'post' => $_POST['post'], 'active' => $_POST['active']);
            $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);
            $this -> upload -> do_upload();
            $data = array('upload_data' => $this->upload->data());
            $this -> post_m -> insert_post($data);
            redirect(base_url() . 'posts/index_admin');
        } else {

            $this -> load -> view('admin/post_new', $data);

        }

    }

view Code

new post:

<?php if ($errors){ ?>
    <?php echo $errors ?>
<?php } ?>
<form action="<?php echo base_url()?>posts/new_post" method="post">
<p><?php echo form_textarea('title'); ?></p>
<p><?php echo form_textarea('post'); ?></p>
<input type="file" name="userfile" size="20" />
<p>Status: <select name="active">
            <option value="1">Active</<option>
            <option value="0">Un Active</<option>
            </select>

</p>
<p><input type="submit" value="add post" /></p>
</form>

Model Code:

function insert_post($data){
        $this->db->insert('posts', $data);
        return $this->db->insert_id();
    }
  1. Try to use different $config array for form_validation and upload library.

  2. $data = array('upload_data' => $this->upload->data()); in this line, you are completely removing the already assigned array in the line ( $data = array('title' => $_POST['title'], 'post' => $_POST['post'], 'active' => $_POST['active']); ). So title, post, active values will not goto insert_post in the model.

  3. Assign $this->upload->data() to separate array variable and use only filename index to get the uploaded filename and assign to $data['urlfile'] (Check the structure of return array of $this->upload->data()).

  4. date_added, userID columns are missing from $data array.

  5. $data['errors'] = 0; errors column is not available in table, so use separate variable to track errors.