Error on uploading CSV File in Codeigniter - php

Hi I am trying to import an CSV into MYSQL database using A CI Library. But I get this error in Controller that file type is now allowed
Controller:
<?php
class Csv extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->model('csv_model');
$this->load->library('csvimport');
}
function index() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$this->load->view('csvindex', $data);
}
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
/*END OF FILE*/
The Model :
<?php
class Csv_model extends CI_Model {
function __construct() {
parent::__construct();
}
function get_addressbook() {
$query = $this->db->get('addressbook');
if ($query->num_rows() > 0) {
return $query->result_array();
} else {
return FALSE;
}
}
function insert_csv($data) {
$this->db->insert('addressbook', $data);
}
}
/*END OF FILE*/
I am trying to Import A CSV using PHP Codeigniter. Now I am getting an error that
The filetype you are attempting to upload is not allowed.
So as you can see i have kept the allowed file type = csv then also this issue is coming. So please help. Thanks

Instead of changing the mime type you can go with the CALLBACK function
This will add more portability too...
function importcsv() {
$data['addressbook'] = $this->csv_model->get_addressbook();
$data['error'] = ''; //initialize image upload error array to empty
$this->form_validation->set_rules('uploaded_file','Uploaded file', 'trim|callback_chk_attachment');
if($this->form_validation->run()){
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'firstname'=>$row['firstname'],
'lastname'=>$row['lastname'],
'phone'=>$row['phone'],
'email'=>$row['email'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
Call Back function for File Upload validation:
public function chk_attachment() // callback validation for check the attachment extension
{
$file_type = array('.csv');
if(!empty($_FILES['uploaded_file']['name']))
{
$ext = strtolower(strrchr($_FILES['uploaded_file']['name'],"."));
if(in_array($ext,$ext_array))
{
return true;
}
else
{
$this->form_validation->set_message('chk_attachment','Attachment allowed only csv');
return false;
}
}
{
$this->form_validation->set_message('chk_attachment','image field is required');
return false;
}
}

Related

Codeigniter image upload validation with controller and function

I have a small issue on this code for the to add a product on my system I am using V_add_pro function, when the image upload part is coming I am facing some issues to validate, so that I used a different function to validate through callback, its not working. the main issue is i am saving the image name only to the database, so how to return the image name only?
public function v_add_pro(){
$this->load->model('B_menu');
$data = array('status' => false, 'msg' => array());
$this->load->library('form_validation');
$this->form_validation->set_rules("pro_name", "name needed", "trim|required");
$this->form_validation->set_rules("pro_price", "price needed", "trim|required");
$this->form_validation->set_rules("pro_desc", "description is needed", "trim|required");
$this->form_validation->set_rules("dropzone", "select an image", "trim|required|callback_validate_image");
$this->form_validation->set_rules("pro_cat", "please select a category","callback_check_default|trim|required");
$this->form_validation->set_error_delimiters('<p class="text-danger">','</p>');
if ($this->form_validation->run()) {
$data['status'] = true;
$pro_data = array(
'pname' => $this->input->post('pro_name'),
'pprice' => $this->input->post('pro_price'),
'pdesc' => $this->input->post('pro_desc'),
'pimage' =>$this->input->post('dropzone'),
'catid' => $this->input->post('pro_cat'),
);
$this->B_menu->add($pro_data);
} else {
foreach ($_POST as $key => $value) {
$data['msg'][$key] = form_error($key);
}
}
echo json_encode($data);
}
//to check the selected value for category
function check_default($post_string)
{
return $post_string == '0' ? FALSE : TRUE;
}
//to upload the image to the correct path
public function validate_image() {
$config = array(
'allowed_types'=>'jpg|png|gif',
'upload_path'=> realpath(APPPATH . '../skin/images'),
'max_size'=>1
);
$this->load->library('upload', $config);
if (!$this->upload->do_upload('dropzone'))
{
$this->form_validation->set_message('validate_image',$this->upload->display_errors());
} else {
$file_info = $this->upload->data();
$img = $file_info['file_name'];
return $img;
}
}
public function validate_image()
{
/* Start: Image Uploading */
$baseurl = $this->config->base_url();
$profile_photo = "";
$profile_path = '';
$config['upload_path'] = './assets/profile_pictures';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
if (!empty($_FILES))
{
$this->file_ext = pathinfo($_FILES['image']['name'], PATHINFO_EXTENSION);
$this->file_name = time() . "." . $this->file_ext;
$config['file_name'] = $this->file_name;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if (!$this->upload->do_upload('image', FALSE))
{
echo $this->upload->display_errors();
$this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());
if ($_FILES['image']['error'] != 4)
{
return false;
}
}
else
{
$profile_photo = $this->file_name;
$profile_path = $baseurl . "assets/profile_pictures";
return $profile_photo;
}
}
/* End: Image Uploading */
To add-ons I am just saving file name as current timestamp thats it. Also return $imagename and also try to echo this
echo $this->upload->display_errors();

how to update database table each time csv file get uploaded in codeigniter?

my csv file looks like:
my database table looks like:
my need is that each time I am uploading the csv file i need to update the database table, I mean if the mid in csv file is present in database mid I have to update that row. And if mid in csv file is not present in database mid I have to insert that new row to the database table.
currently I upload the csv file and data stored in database table successfully.
my controller looks like:
public function importcsv()
{
$data['menu'] = $this->AdminModel->get_menu();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
}
else
{
$file_data = $this->upload->data();
$file_path = './assets/uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path))
{
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row)
{
$mid=$row['mid'];
$insert_data = array(
'mid'=>$mid,
'category'=>$row['category'],
'name'=>$row['name'],
'price'=>$row['price'],
'description'=>$row['description'],
);
$this->AdminModel->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'Admin/menu');
}
else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
I think after fetching the csv file data into the array $insert_data I think I need to compare it with the mid in the database table. How is it possible? I am new to this. thanking in advance.
I made modifications in my controller, its looks:
public function importcsv()
{
$data['menu'] = $this->AdminModel->get_menu();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$this->load->view('csvindex', $data);
}
else
{
$file_data = $this->upload->data();
$file_path = './assets/uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path))
{
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row)
{
$data1['mid']=$row['mid'];
$data1['category']=$row['category'];
$data1['name']=$row['name'];
$data1['price']=$row['price'];
$data1['description']=$row['description'];
if($this->db->where('mid', $data1['mid']))
{
$this->db->update('menu', $data1);
}
if($this->db->where("mid !=",$data1['mid']))
{
$this->db->insert('menu', $data1);
}
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'Admin/menu');
}
else
{
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
Now I can update data By
if($this->db->where('mid', $data1['mid']))
{
$this->db->update('menu', $data1);
}
its works fine, but using condition:
if($this->db->where("mid !=",$data1['mid']))
{
$this->db->insert('menu', $data1);
}
the whole csv file data is reentered into the table menu. I need to compare mid in the menu table and mid in the csv file, if mid in the csv file not present in menu table, I need to insert that corresponding record into the menu table.
for that what all changes should I have to done in the code?
Got a solution. Thank u all for your support and time.
public function importcsv()
{
$data['menu'] = $this->AdminModel->get_menu();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './assets/uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload())
{
$data['error'] = $this->upload->display_errors();
$this->load->view('admin/csvindex', $data);
}
else
{
$file_data = $this->upload->data();
$file_path = './assets/uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path))
{
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row)
{
$data1['mid']=$row['mid'];
$data1['category']=$row['category'];
$data1['name']=$row['name'];
$data1['price']=$row['price'];
$data1['description']=$row['description'];
$this->db->where('mid', $data1['mid']);
$q= $this->db->get('menu');
if( $q->num_rows() > 0 )
{
$this->db->where('mid',$data1['mid']);
$this->db->update('menu',$data1);
}
else
{
$this->db->set('mid',$data1['mid']);
$this->db->insert('menu', $data1);
}
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'Admin/menu');
}
else
{
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
Logic:
If data is already there in the database. Then you have to compare database field with CSV field. If both are matching then update data else insert data.
Thanks

uploading csv not worked properly

When I upload the csv file only first data is uploaded.
This is my controller.
public function uploadbusinesstype()
{
$config['upload_path'] = APPPATH.'/assets/upload/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '5000';
$replace = '"';
$this->load->library('upload', $config);
$this->load->database();
if ( ! $this->upload->do_upload('file_name'))
{
$error = array('error' => $this->upload->display_errors());
$this->session->set_flashdata('msg_excel','Choose a .csv file to upload');
redirect(base_url().'admin/businesstype/managecategories');
}
else
{
$data = array('upload_data' => $this->upload->data());
$userfile = $data['upload_data']['file_name'];
$this->load->library('csvreader');
$upload_data = $this->upload->data();
$file = $upload_data['full_path'];
$file_name = $upload_data['userfile'];
$data = $this->csvreader->parse_file($file);
foreach($data as $row)
{
if($row['main_type_name']=='')
{
$this->session->set_flashdata('msg_excel','Please check the Type Name.It is empty');
redirect(base_url().'admin/businesstype/managecategories');
}
else if(!preg_match("/^[a-zA-Z& ]+$/",$row['main_type_name']))
{
$this->session->set_flashdata('msg_excel','Please check the Type Name.Only alphabets are allowed');
redirect(base_url().'admin/businesstype/managecategories');
}
else
{
$results_array = array(
'type_id' => $row['type_id'],
'main_type_name' => $row['main_type_name']
);
$this->load->model('admin/businesstype_model');
$this->businesstype_model->catupload($results_array);
}
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesstype/managecategories');
}
}
}
This is my model
function catupload($results_array)
{
$this->db->insert('cr_main_shop_type', $results_array);
}
Here There is main type name is there.when i gave accessories,watch and phone as main type name in csv. only first value will enter in the database.
Try this..
Add all values to array and pass array to model "businesstype_model"
$results_array=array();
foreach($data as $row)
{
if($row['main_type_name']=='')
{
$this->session->set_flashdata('msg_excel','Please check the Type Name.It is empty');
redirect(base_url().'admin/businesstype/managecategories');
}
else if(!preg_match("/^[a-zA-Z& ]+$/",$row['main_type_name']))
{
$this->session->set_flashdata('msg_excel','Please check the Type Name.Only alphabets are allowed');
redirect(base_url().'admin/businesstype/managecategories');
}
else
{
//Store values to array
$results_array[] = array(
'type_id' => $row['type_id'],
'main_type_name' => $row['main_type_name']
);
}
if(count($results_array))
{
$this->load->model('admin/businesstype_model');
$this->businesstype_model->catupload($results_array);
}
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesstype/managecategories');
}
else
{
$results_array = array(
'type_id' => $row['type_id'],
'main_type_name' => $row['main_type_name']
);
$this->load->model('admin/businesstype_model');
$this->businesstype_model->catupload($results_array);
}
}
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesstype/managecategories')
}
}
i got it by using this method

CSV upload not working correctly

In this, I want to upload csv files. Validation is not correct but without validation its working.
This is my controller:
public function uploadstatetype()
{
$config['upload_path'] = APPPATH.'/assets/upload/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '5000';
with = ' ';
$replace = '"';
$this->load->library('upload', $config);
$this->load->database();
if ( ! $this->upload->do_upload('file_name'))
{
$error = array('error' => $this->upload->display_errors());
$this->managestate($error);
}
else
{
//Insert file info into database
$data = array('upload_data' => $this->upload->data());
$userfile = $data['upload_data']['file_name'];
$this->load->library('csvreader');
$upload_data = $this->upload->data();
$this->load->library('csvreader');
$file = $upload_data['full_path'];
$file_name = $upload_data['userfile'];
$data = $this->csvreader->parse_file($file);
foreach($data as $row)
{
if(($row['state_id']=='')||($row['state_name']==''))
{
$this->session->set_flashdata('msg_excel','Please check the details in the file, some details are empty.');
redirect(base_url().'admin/businesslocation/managestate');
}
else
{
$results_array = array(
'state_id' => $row['state_id'],
'state_name' => $row['state_name']
);
$this->load->model('admin/businesslocation_model');
$this->businesslocation_model->stateupload($results_array);
$success_message='Successfully Upload!';
$this->session->set_flashdata('success_message',$success_message);
redirect(base_url().'admin/businesslocation/managestate');
}
}
}
}
And this is my model:
function stateupload($results_array)
{
$this->db->insert('cr_state', $results_array);
}
For eg state_id=1 and state_name="kerala". Then insert is working,when condition is not checked. But when if condition is given it's not working.
Change your condition like this and try
if(empty($row['state_id'])||(empty($row['state_name']))){

Viewing files from database tables using Codeigniter

I am trying to view my image files taken from the database and i have no idea why i get a undefined variable when loading my view.
Pretty much I am just trying to view the imagenames stored in my database images.
Any help would be great thank you.
Here are the errors i receive when viewing in browser
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: imagename
Filename: layouts/home.php
Line Number: 8
A PHP Error was encountered
Severity: Warning
Message: Invalid argument supplied for foreach()
Filename: layouts/home.php
Line Number: 8
Here is my Controller
class Home extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->library('upload');
}
function index() {
$this->load->model('index_model');
$foldername['foldername'] = $this->index_model->getFoldernames();
$imagename['imagename'] = $this->index_model->getImagenames();
$this->load->view('layouts/home', $foldername, $imagename, array('error' => ' ' ));
}
function create() {
if(array_key_exists('createFolder',$_POST)){
$data = array(
'folderName' => $this->input->post('folderName')
);
$data = str_replace(' ', '_', $data);
$this->index_model->createFolder($data);
}
$this->foldercreated();
}
function delete() {
$this->load->model('index_model');
$foldername['foldername'] = $this->index_model->getFoldernames();
$this->load->view('layouts/delete', $foldername);
}
function deleteFolder() {
if($this->input->post('checkbox') !== false) {
$checkbox = $this->input->post('checkbox');
$this->index_model->deleteFolder($checkbox);
}
$this->folderdeleted();
}
function foldercreated() {
$this->load->view('partials/foldercreated');
}
function folderdeleted() {
$this->load->view('partials/folderdeleted');
}
function do_upload() {
$config['source_image'] = $this->upload->upload_path.$this->upload->file_name;
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '0';
$config['max_width'] = '0';
$config['max_height'] = '0';
$this->upload->initialize($config);
$this->load->library('upload', $config);
if ( !$this->upload->do_upload('userfile'))
{
// echo '<p>IMAGE NOT WORKING</p>'. '<br/><p>' . $this->upload->display_errors() . '</p>';
$uploadError = $this->upload->display_errors();
$this->load->view('partials/upload_error', $uploadError);
}
else
{
// $imagefile = array('upload_data' => $this->upload->data());
$upload_data = $this->upload->data();
$db_data = array('imageName' => $upload_data['file_name']);
$this->index_model->addImage($db_data); // replace the tablename
$this->load->view('partials/upload_success', $db_data);
}
}
}
Here is my Model
function getFolderNames() {
$this->db->order_by('id', 'DESC');
$this->db->select('folderName');
$q = $this->db->get('senior');
if($q->num_rows() > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
function getImagenames() {
$this->db->order_by('id', 'DESC');
$this->db->select('imageName');
$query = $this->db->get('images');
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
$data[] = $row;
}
return $data;
}
}
And Here is my View
<div id="imagefiles">
<?php
foreach ($imagename as $img) { ?>
<div><?php echo $img->imageName; ?></div>
<?php } ?>
</div>
You aren't passing data to your view correctly.
You have this: $this->load->view('layouts/home', $foldername, $imagename, array('error' => ' ' ));
Your second parameter should be an array of data that you want to pass to your view. Try something like this:
$data['foldername'] = $this->index_model->getFoldernames();
$data['imagename'] = $this->index_model->getImagenames();
$this->load->view('layouts/home', $data);
Please check the CodeIgniter documentation for more info.

Categories