I need to insert multiple values in the checkbox in Codeigniter. how I can write this in the controller.
I tried so many but the values not inserting .
View.Php
<div class="custom-file">
<input type="checkbox" name="size[]" value="Medium"> M
<input type="checkbox" name="size[]" value="Large">L
<input type="checkbox" name="size[]" value="XL"> XL
</div>
Model
public function product_insert($data)
{
// grab user input
$this->db->insert('product', $data);
return $this->db->insert_id();
}
Controller
public function newProduct()
{
$data = array();
$this->load->library('form_validation');
$this->load->library('image_lib');
$this->load->helper('file');
$this->load->helper('string');
// Load the model
$this->load->model('admin/product_model');
$this->load->model('admin/category_model');
$data['category'] = $this->category_model->active_category_listing();
// $data['brand'] = $this->product_model->brand_listing();
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">', '</div>');
// Validating Field
$this->form_validation->set_rules('product_title', 'Title', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('admin/add_product', $data);
}
//insert size checkboxes into database.
$sizeArray = $this->input->post('size'); // Array
$sizeString = implode(",", $sizeArray); // String
else {
$config['upload_path'] = 'uploads/product_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 10024;
$this->load->library('upload', $config);
// upload file to directory
$uploadedFile ='';
if ($this->upload->do_upload('product_img')) {
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $uploadData['full_path'];
$config['new_image'] = 'uploads/product_images/thumb';
$config['create_thumb'] = false;
$config['maintain_ratio'] = TRUE;
$config['width'] = 311;
$config['height'] = 415;
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data['success_msg'] = 'File has been uploaded successfully.';
} else {
$data['error_msg'] = $this->upload->display_errors();
}
// Setting values for tabel columns
$data = array(
'product_title' => $this->input->post('product_title'),
'product_description' => $this->input->post('product_description'),
'product_price' => $this->input->post('product_price'),
'product_discount' => $this->input->post('product_discount'),
'product_quantity' => $this->input->post('product_quantity'),
'sub_category_id' => $this->input->post('sub_category_id'),
'category_id' => $this->input->post('category_id'),
'product_status' => $this->input->post('product_status'),
'product_img' => $uploadedFile,
'product_key' => random_string('alnum',8),
'product_cuttingprice' => $this->input->post('product_cuttingprice'),
'size'=>$sizeString);
);
// Transfering data to Model
$prdID = $this->product_model->product_insert($data);
$upImg = $this->uploadAddtnlImages($prdID);
$this->session->set_flashdata('msg', 'Product Added Successfully');
redirect('admin/product/listProduct/', 'refresh');
}
}
View:-
You must do all name checkbox as an array like this.
<div class="custom-file">
<input type="checkbox" name="size[]" value="Medium"> M
<input type="checkbox" name="size[]" value="Large">L
<input type="checkbox" name="size[]" value="XL"> XL
</div>
Controller:-
public function newProduct()
{
$data = array();
$this->load->library('form_validation');
$this->load->library('image_lib');
$this->load->helper('file');
$this->load->helper('string');
// Load the model
$this->load->model('admin/product_model');
$this->load->model('admin/category_model');
$data['category'] = $this->category_model->active_category_listing();
// $data['brand'] = $this->product_model->brand_listing();
$this->form_validation->set_error_delimiters('<div class="alert alert-danger">','</div>');
// Validating Field
$this->form_validation->set_rules('product_title', 'Title', 'required');
if ($this->form_validation->run() == false) {
$this->load->view('admin/add_product', $data);
}
else {
$config['upload_path'] = 'uploads/product_images/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = 10024;
$this->load->library('upload', $config);
// upload file to directory
$uploadedFile ='';
if ($this->upload->do_upload('product_img')) {
$uploadData = $this->upload->data();
$uploadedFile = $uploadData['file_name'];
$config['image_library'] = 'gd2';
$config['source_image'] = $uploadData['full_path'];
$config['new_image'] = 'uploads/product_images/thumb';
$config['create_thumb'] = false;
$config['maintain_ratio'] = TRUE;
$config['width'] = 311;
$config['height'] = 415;
$this->image_lib->initialize($config);
$this->load->library('image_lib', $config);
$this->image_lib->resize();
$data['success_msg'] = 'File has been uploaded successfully.';
} else {
$data['error_msg'] = $this->upload->display_errors();
}
//insert size checkboxes into database.
$sizeArray = $this->input->post('size'); // Array
$sizeString = implode(",", $sizeArray); // String
// Setting values for tabel columns
$data = array(
'product_title' => $this->input->post('product_title'),
'product_description' => $this->input->post('product_description'),
'product_price' => $this->input->post('product_price'),
'product_discount' => $this->input->post('product_discount'),
'product_quantity' => $this->input->post('product_quantity'),
'sub_category_id' => $this->input->post('sub_category_id'),
'category_id' => $this->input->post('category_id'),
'product_status' => $this->input->post('product_status'),
'product_img' => $uploadedFile,
'product_key' => random_string('alnum',8),
'product_cuttingprice' => $this->input->post('product_cuttingprice'),
'size'=>$sizeString);
);
// Transfering data to Model
$prdID = $this->product_model->product_insert($data);
$upImg = $this->uploadAddtnlImages($prdID);
$this->session->set_flashdata('msg', 'Product Added Successfully');
redirect('admin/product/listProduct/', 'refresh');
}
}
Model Code:-
public function product_insert($data)
{
// grab user input
$this->db->insert('product', $data);
return $this->db->insert_id();
}
Note:- For More info regarding implode().
The implode() function returns a string from the elements of an array.
https://www.php.net/manual/en/function.implode.php
Related
Codeigniter when i update the form others are updating but image path disappears
Form Submit
user name update
password update
image url delete
Form Submit
user name update
password update
Not -> image url delete
CONTROLLER
public function profil_guncelle($id)
{
if(!empty($_FILES['avatar']['name'])){
$config['upload_path'] = 'uploads';
$config['allowed_types'] = 'jpg|jpeg|png|gif';
$config['width'] = 150;
$config['height'] = 50;
$config['file_name'] = $_FILES['avatar']['name'];
$this->load->library('upload',$config);
$this->upload->initialize($config);
if($this->upload->do_upload('avatar')){
$uploadData = $this->upload->data();
$picture = $uploadData['file_name'];
}else{
$picture = '';
}
}else{
$picture = '';
}
$this->form_validation->set_rules('user_pass', 'Parola', 'trim|required');
$this->form_validation->set_rules('user_mail', 'E-Posta', 'trim|required');
if ($this->form_validation->run() == FALSE) {
$this->session->set_userdata('profil_guncelle', validation_errors());
$upload_error = array('error' => $this->upload->display_errors());
redirect(base_url().'admin/users/profil/'.$id);
}else{
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
'avatar' => $picture
);
if ($this->Database_Model->profil_guncelle($data, $id) ==true) {
$this->session->set_flashdata('profil_guncelle', 'Bilgileriniz başarıyla güncellendi.');
redirect(base_url().'admin/users/profil/'.$id);
}
}
}
}
DATABASE MODEL
public function profil_guncelle($data, $id){
$this->db->set($data);
$this->db->where('id', $id);
if ($this->db->update('users') ===true) {
return true;
}else{
return false;
}
}
First you are set $picture become '' if $_FILES['avatar']['name'] is empty.
than when you are trying update data
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
'avatar' => $picture
);
of course $picture will be set to '' if the images files are empty. you change the array become :
$data=array(
'user_pass' => $this->input->post('user_pass'),
'user_mail' => $this->input->post('user_mail'),
);
if($picture != ''){
$data['avatar'] = $picture;
}
upload library
function upload($upload_path = '', $file_name = ''){
$config = $this->config($upload_path);
$this->CI->load->library('upload' ,$config);
//thuc hien upload
if($this->CI->upload->do_upload($file_name)){
$data = $this->CI->upload->data();
}
else{
//khong upload thanh cong
$data = $this->CI->upload->display_error();
}
return $data;
}
function config($upload_path = ''){
//Khai bao bien cau hinh
$config = array();
//thuc mục chứa file
$config['upload_path'] = $upload_path;
//Định dạng file được phép tải
$config['allowed_types'] = 'jpg|png|gif';
//Dung lượng tối đa
$config['max_size'] = '500';
//Chiều rộng tối đa
$config['max_width'] = '1500';
//Chiều cao tối đa
$config['max_height'] = '1500';
//load thư viện upload
$this->CI->load->library('upload', $config);
return $config;
}
edit action
function edit(){
$id = $this->uri->rsegment('3');
$news = $this->news_model->get_info($id);
if(!$news){
$this->session->set_flashdata('message', 'Không tồn tại bài viết này');
redirect(admin_url('news'));
}
$this->data['news'] = $news;
$this->load->library('form_validation'); //load thư viện
$this->load->helper('form'); //load helper
/*===============================================validate và update data===========================================*/
if( $this->input->post() ){
$this->form_validation->set_rules('title' ,'Tiêu đề bài viết ','required');
$this->form_validation->set_rules('content' ,'Nội dung bài viết','required');
if( $this->form_validation-> run()){
$this->load->library('upload_library');
$upload_path = './upload/news';
$upload_data = $this->upload_library->upload($upload_path, 'image');
$image_link = $this->news_model->get_info($id, 'image_link') ;
if( isset($upload_data['file_name']) ){
$image_link = $upload_data['file_name'];
}
$data = array(
'title' => $this->input->post('title'),
'content' => $this->input->post('content'),
'image_link' => $image_link,
'meta_desc' => $this->input->post('meta_desc'),
'meta_key' => $this->input->post('meta_key'),
'created' => now()
);
if($this->news_model->update($news->id , $data)){
$this->session->set_flashdata('message', 'Cập nhật dữ liệu thành công');
}
else{
$this->session->set_flashdata('message', 'Không cập nhật dữ liệu thành công');
}
//chuyển tới trang danh sách quản trị viên
redirect(admin_url('news'));
}
}
$this->data['temp'] = 'admin/news/edit';
$this->load->view('admin/main' , $this->data);
}
I edited the data are not required to upload photos
when I clicked update button without upload file error occurred
$data = $this->CI->upload->display_error();
this is wrong method call. It should be like this
$data = $this->CI->upload->display_errors();
I have a form with four fileds like contactemail,contactname,category,comments as of now now i have to add image and doc input in a form,using form i have inserted data to db,how to upload image and doc in codeignatior on form submit
images need to upload in image folder and doc in docs folder
Here is my controller
public function form() {
$this->load->helper('form');
$data = $this->login_model->form();
//loading views
load-view-header
load view page
load-view-footer
}
here my model function
public function form() {
$contactemail = $this->input->post('contactemail');
$contactname = $this->input->post('contactname');
$category = $this->input->post('category');
$comments = $this->input->post('comments');
$data = array(
'contactemail' => $email,
'contactname' => $name,
'category' => $category,
'comments' => $comments
);
$this->db->insert('contact', $data);
return $data;
}
Here is an example. This was put together quickly and is completely untested...at best there may be errors and at worst memory has failed me and I totally missed something but may be a useful example. Let me know if it helps?
View:
<?php echo $error;?>
<?php echo form_open_multipart('upload/do_upload');?>
<!-- your other form fields for email, name, category, comments can go here-->
<input type="file" name="image" size="20" />
<input type="file" name="doc" size="20" />
<br /><br />
<input type="submit" value="Submit" />
</form>
Controller:
function form()
{
$this->load->helper(array('form', 'url'));
$config['upload_path'] = './images/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '2048';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$this->load->library('upload', $config);
$data['error'] = "";
//it would be good to be using the form validation class but here is a quick and dirty check for the submit
if (isset($_POST['submit']))
{
if ( ! $this->upload->do_upload('image'))
{
$data['error'] = $this->upload->display_errors();
}
else
{
$image_upload_data = $this->upload->data();
}
unset($config);
$config['upload_path'] = './docs/';
$config['allowed_types'] = 'doc|docx|txt';
$config['max_size'] = '2048';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('doc'))
{
$data['error'] .= "<br />".$this->upload->display_errors();
}
else
{
$doc_upload_data = $this->upload->data();
}
if(!empty($data['error']))
{
$this->load->view('form', $data);
}
else
{
$contactemail = $this->input->post('contactemail');
$contactname = $this->input->post('contactname');
$category = $this->input->post('category');
$comments = $this->input->post('comments');
$doc_file = $doc_upload_data['full_path'];
$image_file = $image_upload_data['full_path'];
$form_data = array(
'contactemail' => $email,
'contactname' => $name,
'category' => $category,
'comments' => $comments,
'doc_file' => $doc_file
);
$image_data['image_name'] = $image_file;
$this->login_model->form($form_data,$image_data);
$this->load->view('upload_success', $data);
}
}
else
{
$this->load->view('form', $data);
}
}
Model
public function form($form_data,$image_data) {
$this->db->insert('contact', $image_data);
$image_data['d_fk'] = $this->db->insert_id();
$this->db->insert('images', $image_data);
}
I am inserting some data into the database in my Codeigniter controller
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$this->favourite_db->add_soothingmemory($data);
$count = array('soothingcount' => $query);
$this->favourite_db->updateusercount($count);
$this->load->view('positivepast', $data);
}
}
Model
function add_soothingmemory($data) {
$this->load->database();
$this->db->insert('soothingmemory', $data);
$this->set_session();
return $data;
}
The problem is when the value is inserted into the database it inserts three times creating multiple/duplicate rows.
I had the same problem,
anyhow, in your model,
$this->db->limit(1);
$this->db->insert('soothingmemory', $data);
that way duplicates will be avoided.
Hope it helps
Make the following changes:
function addsoothingmemory() {
$config['upload_path'] = './uploads2/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '500000';
$config['max_width'] = '100024';
$config['max_height'] = '100768';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = array('error' => $this->upload->display_errors());
$this->load->view('soothing', $error);
} else {
$imagedata = $this->upload->data();
$data = array(
'image_path' => $imagedata['file_name'],
'title' => $this->input->post('title'),
'user_id' => $this->session->userdata("user_id"),
'feelingrate' => $this->session->userdata("feelingrate"),
'description' => $this->input->post('description')
);
$query = $this->favourite_db->getsoothingcount() + 1;
$save = $this->favourite_db->add_soothingmemory($data);
// Move this code into the model
// $count = array('soothingcount' => $query);
if($save == true){
$this->favourite_db->updateusercount($query);
$this->load->view('positivepast', $data);
}else{
//do something else
}
}
}
In the model
function add_soothingmemory($data) {
$this->load->database();
$save = $this->db->insert('soothingmemory', $data);
//This condition will check, if the $data was save
if($save == true){
//If is save, it will set the session and return true
$this->set_session();
return true;
}else{
return false;
}
}
I'm curious to know in $this->upload->do_upload('img') field name is passing mandotory not.I have seen several example in stackoverflow where do_upload() not taking any argument as file field name.But in case of mine without field name file not uploaded.I want to know which is correct syntax?
2)How do i bypass the file upload validation when there is no file being uploaded.If there is no file(image) in the form then $this->upload->display_errors() will not be called.my code is below
function add()
{
if ($this->input->server('REQUEST_METHOD') === 'POST')
{
$this->form_validation->set_rules('category', 'Category Name', 'required');
if ($this->form_validation->run())
{
$data_to_store = array(
'category' => $this->input->post('category'),
'description' => $this->input->post('description'),
'parent'=>'0'
);
$last_id=$this->admin_category_model->add_category($data_to_store);
$config['upload_path'] ='./uploads/';
$config['allowed_types'] = 'gif|jpg|png|GIF|JPG|PNG';
$config['remove_spaces'] = TRUE;
$config['max_size'] = '0';
$config['file_name'] =$last_id.'_'.$_FILES['img']['name'];
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if($this->upload->do_upload('img'))
{
$data = array('upload_data' => $this->upload->data());
$config2['image_library'] = 'gd2';
$config2['source_image'] = $data['upload_data']['full_path'];
$config2['new_image'] ='./uploads/thumb/'.$data['upload_data']['file_name'];
$config2['create_thumb'] = FALSE;
$config2['maintain_ratio'] = TRUE;
$config2['width'] = 35;
$config2['height'] = 35;
$this->load->library('image_lib',$config2);
$this->image_lib->resize();
$data_to_store = array(
'img' => $config['file_name'],
);
$this->admin_category_model->update_category($last_id,$data_to_store);
$this->session->set_flashdata('flash_message', 'Record Added');
redirect('admin_category/index');
}
else
{
$data['error']=$this->upload->display_errors();
}
}
}
$data['title']='Add Category';
$data['main_content'] = 'admin/add_category';
$this->load->view('admin/includes/template', $data);
}
1st) No, not necessary, by default it will take the name userfile.
2nd) Say for example your fieldname is img check like this:
if( $_FILES['img']['name'] != "" ){
//your upload code here
}