As questioned above I want to upload multiple images for single product into database table (table will contain only image paths).
My code is:
Controller - productController.php
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->model('productModel');
}
public function index()
{
$data['product_list'] = $this->productModel->get_all_products();
$this->load->view('productDisplay', $data);
}
public function add_form()
{
$this->load->view('insertProduct');
}
private function setup_upload_option()
{
$config = array();
$config['upload_path'] = './uploadProductImages/';
$config['allowed_types'] = 'jpg|png|gif|jpeg';
$config['encrypt_type'] = true;
$config['overwrite'] = false;
return $config;
}
public function insert_new_product()
{
$this->load->library('upload');
$files = $_FILES;
$count = count($_FILES['images']['name']);
for($i=0;$i<$count;$i++)
{
$_FILES['images']['name'] = $files['images']['name'][$i];
$_FILES['images']['type'] = $files['images']['type'][$i];
$_FILES['images']['tmp_name'] = $files['images']['tmp_name'][$i];
$_FILES['images']['size'] = $files['images']['size'][$i];
$_FILES['images']['error'] = $files['images']['error'][$i];
$this->upload->initialize($this->setup_upload_option());
if($this->upload->do_upload() == false)
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('insertProduct', $error);
}
else
{
$upload_data = $this->upload->data();
$udata['name'] = $this->input->post('name');
$udata['manufacturer'] = $this->input->post('manufacturer');
$udata['price'] = $this->input->post('price');
$udata['images'] = $upload_data['file_name'];
$res = $this->productModel->insert_products_to_db($udata);
if($res)
{
header('location:'.base_url()."index.php/productController/".$this->index());
}
}
}
Model - productModel.php
public function insert_products_to_db($data)
{
return $this->db->insert('product_info', $data);
}
View - insertProduct.php
<?php if(isset($error)){echo $error;}?>
<form method="post" action="<?php echo base_url();?>index.php/productController/insert_new_product" enctype="multipart/form-data">
<table >
<tr>
<th >Product Name</th>
<td ><input type="text" name="name" /></td>
</tr>
<tr>
<th >Manufacturer</th>
<td><input type="text" name="manufacturer" /></td>
</tr>
<tr>
<th >Price</th>
<td><input type="text" name="price"/></td>
</tr>
<tr>
<th >Images</th>
<td><input type="file" name="images[]" multiple=""/></td>
</tr>
<tr>
<th > </th>
<td><input type="submit" name="submit" value="Add" /></td>
</tr>
</table>
</form>
My database table contains 5 fields p_id, name, manufacturer,price and images. And after running this code, when I clicks on Add it do not show any error or do not redirect to controller but it stays on same page and no any image is present in uploadProductImages
and also no new product will insert in database table.
Any help for this new learner will be appreciated.