Как добавить несколько изображений в базу данных

#php #image #codeigniter #upload

#php #изображение #codeigniter #загрузка

Вопрос:

Я пытаюсь добавить несколько изображений, одно для изображений баннера, другое несколько изображений для изображений галереи, но когда я пытаюсь добавить изображение, оно выдает ошибку:

диалог между массивом и строкой.

Я хочу добавить одно изображение в ту же таблицу, а другие изображения в другую таблицу, поэтому, когда я покажу запись в своем представлении, я легко смогу использовать одно изображение баннера.

Я буду очень благодарен, если кто-нибудь поможет мне в этом. итак, вот мое мнение.

  <div class="col-lg-12">
     <label for="main image">Upload Main Image: </label><br>
     <input type="file" name="image_file">
 </div><br><br><br>
                                       
 <div class="col-lg-12">
     <label for="Image name">Upload Mutiple Images:</label><br>
     <input type="file" required name="image_name[]" multiple/><br>
 </div>

  
 // Model

function addnews($data, $id ='')
{
  
    $title       = $this->input->post('title');
    $address     = $this->input->post('address');
    $city        = $this->input->post('city');
    $zip         = $this->input->post('zipcode');
    $type        = $this->input->post('propertytype');
    $status      = $this->input->post('status');
    $price       = $this->input->post('price');
    $description = $this->input->post('Description');
    $userfile    = $this->input->post('[image_file]');
    $bedrooms    = $this->input->post('bedrooms');
    $rooms       = $this->input->post('rooms');
    $bath        = $this->input->post('bathroom');
    $garages     = $this->input->post('gerages');
    $date        = $this->input->post('date');
    $amenities   = implode(',',$this->input->post('check'));
                   

  
    $w = array (
        'title'   => $title,
        'address' => $address,
        'city'    => $city,
        'zip'     => $zip,
        'type'    => $type,
        'status'  => $status,
        'description' => $description,
        'bedrooms' => $bedrooms,
        'rooms'   => $rooms,
        'price'   => $price,
        'userfile' => $data,
        'bath' => $bath,
        'date' => $date,
        'garages' => $garages,
        'amenities' => $amenities
    );

    
    $this->db->insert_batch("property", $w);
    $id = $this->db->insert_id();

    foreach ($data as $row) { // here data is from parameter
        $data1[] = array(
            'property_id' => $id,  //Insert Inserted id
            'image_name'  => $row['file_name'] // this line is changed
        );
    }
   } 
 // My controller.

public function addlisting()
{
        
    $this->load->library('upload');
    $config['upload_path']='./uploads';
    $config['allowed_types']='*';
    $this->upload->initialize($config);
    $this->load->library('upload', $config);
    if (!$this->upload->do_upload('image_file')) {  
        $this->session->set_flashdata('msg',"Failed To Apply. Please Check All The Fields.");
        redirect(site_url('Welcome/add_listing'));
    } else {
        $fd = $this->upload->data();
        $fn = $fd['file_name'];
        //$this->User_model->addnews($fn);
        $image = array();
        $ImageCount = count($_FILES['image_name']['name']);
        
        for ($i = 0; $i < $ImageCount; $i  ) {
            $_FILES['file']['name'] = $_FILES['image_name']['name'][$i];
            $_FILES['file']['type'] = $_FILES['image_name']['type'][$i];
            $_FILES['file']['tmp_name'] = $_FILES['image_name']['tmp_name'][$i];
            $_FILES['file']['error'] = $_FILES['image_name']['error'][$i];
            $_FILES['file']['size'] = $_FILES['image_name']['size'][$i];

            // File upload configuration
            $uploadPath = './uploads';
            $config['upload_path'] = $uploadPath;
            $config['allowed_types'] = 'jpg|jpeg|png|gif';

            // Load and initialize upload library
            $this->load->library('upload', $config);
            $this->upload->initialize($config);

            // Upload file to server
            if ($this->upload->do_upload('file')) {
                // Uploaded file data
                $imageData = $this->upload->data();
                $uploadImgData[$i]['file_name'] = $imageData['file_name'];
            } else {
                $this->session->set_flashdata('msg',"Error while uploading Data");
                // $this->User_model->addnews($uploadImgData);
                redirect(site_url('Welcome/add_listing'));
            }
        }
        
        if (!empty($uploadImgData)) {
            //Insert files data into the database

            $this->User_model->addnews($uploadImgData);
            $this->User_model->addnews($fn);
            // $query = implode(",",$uploadImgData);
            // $insert = $this->User_model->add($uploadImgData);
           $this->session->set_flashdata('msg',"Property Uploaded successfully");   
           redirect('Welcome/add_listing');   
        }
    
 

}

Ответ №1:

попробуйте изменить имя или конфигурационный массив

 public function add_model()
    {
        $this->before_login();
        $data = array();
        $data['mode'] = "ADD";
        $db_name = 'para';
        $table = 'models';
        $sess = $this->session->userdata('admin');
        $data['a_name'] = $sess['name'];

        $data['record'] = $this->Paramodel->select('brand','brand_name,id');

        if($this->input->post('submit'))
        {
            $this->Database->add_new_model($table,$db_name);
            foreach($_POST as $key=>$value)
            {
                $key=trim($value); 
            }
            // Form Validation Run
            if($this->form_validation->run('add_model'))
            {
                if(strlen($_FILES['model_display_picture']['name']) > 0)
                {
                    $config['upload_path']   = './assets/Model/';
                    $config['allowed_types'] = 'jpg|jpeg|png';  
                    $config['max_size']      = 2048;
                    $config['encrypt_name'] = TRUE; 
                    
                    // directry Path
                    $this->load->library('upload',$config);

                    $slug = $this->clean_url($model_name);
                    
                    $this->upload->initialize($config);
                    if($this->upload->do_upload('model_display_picture'))
                    {
                        $result=$this->last_record('models')[0]['setord'];
                        // echo "<pre>";
                        // print_r($result);
                        // exit;
                        if($result == "" ){ $last_setord_no = 1;  }else{ $last_setord_no = $result 1; }

                            $image_path = './assets/Model/'.$this->upload->data('file_name');
                            // INSERT DATA 
                            $ins['brand_id'] = $brand_id;
                            $ins['model_type'] = $model_type;
                            $ins['model_name'] = $model_name;
                            $ins['model_description'] = $model_description;
                            $ins['model_display_image'] = $image_path;
                            $ins['status'] = $status;
                            $ins['slug'] = $slug;
                            $ins['setord'] = $last_setord_no;
                            $ins['meta_title'] = addslashes($meta_title);
                            $ins['meta_descryption'] = $meta_description;
                            $ins['meta_keywords'] = $meta_keywords;
                            $ins['u_create_date'] = date('Y-m-d H:i:s');

                            // INSERT QUERY
                            $insert = $this->Paramodel->insert('models',$ins);
                            $insert_id = $this->db->insert_id();
                            $this->_create_thumbs($this->upload->data('file_name'));

                            // INSERT SUCCESS CONDITION
                            if( $insert == 1 )
                            {
                                $count = count($_FILES['model_images']['name']);
                                if( $count > 0)
                                {
                                    
                                    $this->Database->model_image('model_image');
                                    for($i = 0 ; $i < $count ; $i   )
                                    {
                                            $_FILES['single']['name'] = $_FILES['model_images']['name'][$i];
                                            $_FILES['single']['type'] = $_FILES['model_images']['type'][$i];
                                            $_FILES['single']['tmp_name'] = $_FILES['model_images']['tmp_name'][$i];
                                            $_FILES['single']['size'] = $_FILES['model_images']['size'][$i];
                                            $_FILES['single']['error'] = $_FILES['model_images']['error'][$i];
                                            
                                            $config1['upload_path']   ='./assets/Model/';
                                            $config1['allowed_types'] = 'jpg|jpeg|png'; 
                                            $config1['max_size']      = 2048;
                                            $config1['encrypt_name'] = TRUE;    
                                            // echo "<pre>";
                                            // print_r($config1);

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

                                            // echo "<pre>";
                                            // print_r($_FILES['single']);
                                            // echo "------------------";
                                            if($this->upload->do_upload('single'))
                                            {
                                                // echo "<pre>";
                                                // print_r($config1);
                                                
                                                $images_path = './assets/Model/'.$this->upload->data('file_name');
                                                $ins_up['model_id'] = $insert_id;
                                                $ins_up['model_image'] = $images_path;
                                                
                                                $result = $this->Paramodel->insert('model_image',$ins_up);
                                                $this->_create_thumbs($this->upload->data('file_name'));
                                                if($result == 1)
                                                {
                                                    $this->session->set_flashdata('insert','Model Insert SuccessFully.');
                                                    redirect('manage-models');
                                                }
                                            }
                                            else
                                            {
                                                $data['error'][$i] = array('error' => $this->upload->display_errors());
                                            }
                                        
                                    }
                                }
                            }
                    }
                    else
                    {
                        $data['error'][$i] = array('error' => $this->upload->display_errors());
                    }   
                }   
            }
        }
        $this->load->view('admin/add_model',$data);
    } 

мой код таков: попробуйте.