I have noticed that if a cell is empty phpexcel gives it a null value. Is there a way i can replace the null value with any empty string before i loop through the array and store into the database. Below is my code and i am using the codeigniter framework.
public function import(){
$id = $this->session->userdata('company_id');
$directoryname = get_company_full_name($id);
if (!is_dir(FCPATH.'assets/customer_documents/Databases/'.$directoryname)) {
mkdir(FCPATH.'assets/customer_documents/Databases/'.$directoryname, 0777, TRUE);
}
$database_name = $this->input->post('database_name');
// $data['addressbook'] = $this->csv_model->get_addressbook($id);
$data['errors'] = ''; //initialize upload error array to empty
$config['upload_path'] = FCPATH.'assets/customer_documents/Databases/'.$directoryname;
$config['allowed_types'] = '*';
$config['max_size'] = '';
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$data['errors'] = $this->upload->display_errors();
$data['databases'] = $this->database->get_databases($id);
$this->session->set_flashdata($data);
redirect(base_url().'Databases');
} else {
$file_data = $this->upload->data();
$file_ext = $file_data['file_ext'];
// use custom function to determine if filetype is allowed
if (allow_csv_type($file_ext))
{
$file_path = FCPATH.'assets/customer_documents/Databases/'.$directoryname. '/' .$file_data['file_name'];
//read file from path
$objPHPExcel = PHPExcel_IOFactory::load($file_path);
$date_uploaded = date("Y-m-d H:i:s");
if ($objPHPExcel) {
//get only the Cell Collection
$cell_collection = $objPHPExcel->getActiveSheet()->getCellCollection();
//extract to a PHP readable array format
foreach ($cell_collection as $cell) {
$column = $objPHPExcel->getActiveSheet()->getCell($cell)->getColumn();
$row = $objPHPExcel->getActiveSheet()->getCell($cell)->getRow();
$data_value = $objPHPExcel->getActiveSheet()->getCell($cell)->getValue();
//header will/should be in row 1 only. of course this can be modified to suit your need.
if ($row == 1) {
$header[$row][$column] = $data_value;
} else {
$arr_data[$row][$column] = $data_value;
}
}
// array_shift($arr_data); // removes the 1st/header element
//store the database name and details
$database_data = array(
'db_name'=>$database_name,
'company_id' => $id,
'deleted' => 0,
'date_uploaded'=> $date_uploaded
);
$this->database->insert_db($database_data);
$database_id = $this->db->insert_id();
foreach ($arr_data as $row) {
$insert_data = array(
'company_id' => $this->session->userdata('company_id'),
'number'=>$row['A'],
'province'=>$row['B'],
'district'=>$row['C'],
'ward'=>$row['D'],
'farming_type'=>$row['E'],
'commodity'=>$row['F'],
'database_name'=>$database_name,
'db_id' =>$database_id,
'deleted' => 0,
'date_uploaded'=>$date_uploaded
);
$this->database->insert_csv($insert_data, $id);
}
log_message('info', '*****************************Customer with the ID: '.$this->session->userdata('company_id').' and name: '.get_company_full_name($this->session->userdata('company_id')).' uploaded a csv database. The uploder phone number: '.$this->session->userdata('phone').' The database ID: '.$database_id.' The database name: '.$database_name.'*****************************');
$this->session->set_flashdata('success', 'Data Imported Succesfully');
redirect(base_url().'Databases');
} else{
$data['errors'] = "Error occured";
$data['page_class'] = 'Databases-page';
$data['title'] = 'Databases';
$data['content_view'] = 'Databases/index';
$this->template->admin_template($data);
}
}
else {
$this->session->set_flashdata('errors','File type is not allowed!');
redirect('Databases');
}
}
}
}
I am just looking for a way i can add empty sting values on the empty cells that are coming with null values.
Just use a simple array modifier before it reaches PHPExcel.
If performance is an issue, one may consider not to create multiple functions within array_map(). Note that isset() is extremely fast, and this solutions does not call any other functions at all.
$replacements = array(
'search1' => 'replace1',
'search2' => 'replace2',
'search3' => 'replace3'
);
foreach ($a as $key => $value) {
if (isset($replacements[$value])) {
$a[$key] = $replacements[$value];
}
}
See: https://stackoverflow.com/a/32321702/4272537
Related
I have csv with 4 columns. If i select make it shows models then year. I want it to show versions at the 4th box. however nothing happens. i have changed code and it will show versions in the 3rd box and then years disappears. still nothing in 4th box.
Played around with this bit of the code which makes the above effect but cant figure out why the 4th select box dont work.
$makes_models_years_versions = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'/make_model_year_version.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline){
$firstline = false;
continue;
}
$makes_models_years_versions[$line[0]][$line[1]][$line[2]][] = $line[3];
}
COMPLETE CODE BELOW:
function ajax_cf7_populate_values() {
// read the CSV file in the $makes_models_years_versions array
$makes_models_years_versions = array();
$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen($uploads_folder.'/make_model_year_version.csv', 'r');
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline){
$firstline = false;
continue;
}
$makes_models_years_versions[$line[0]][$line[1]][$line[2]][] = $line[3];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'makes' => array_keys($makes_models_years_versions),
'models' => array(),
'years' => array(),
'versions' => array(),
'current_make' => false,
'current_model' => false,
'current_year' => false
);
// collect the posted values from the submitted form
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
$year = key_exists('year', $_POST) ? $_POST['year'] : false;
$version = key_exists('version', $_POST) ? $_POST['version'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = array_keys($makes_models_years_versions[$make]);
if ($model) {
$return_array['current_model'] = $model;
$return_array['years'] = $makes_models_years_versions[$make][$model];
if ($year) {
$return_array['current_year'] = $year;
$return_array['versions'] = $makes_models_years_versions[$make][$model][$year];
if ($version) {
$return_array['current_version'] = $version;
}
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
}
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
I want to pass my last insert id from one table into another function when I test with var_dumb() $ids var contains value but after submiting $ids var contains nothing.
can someone show me how to do it in this code,
thank you
this is my controller :
function save()
{
$judul = $this->input->post('judul');
$isi = $this->input->post('isi');
$kategori = implode(',', $this->input->post('kategori'));
$c_date=date("Y-m-d H:i:s");
$data = array(
'judul' => $judul,
'isi' => $isi,
'kategori' => $kategori,
'publish' => $c_date
);
$ids = $this->text_editor_model->simpan($data);
redirect('text_editor');
$last = $this->upload_image($ids);
}
function upload_image($last)
{
$config['upload_path'] = './berkas/news/';
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 0;
$this->load->library('upload', $config);
var_dump($last);
if ( !$this->upload->do_upload('file')) {
$this->output->set_header('HTTP/1.0 500 Server Error');
exit;
} else {
$file = $this->upload->data();
$this->output
->set_content_type('application/json', 'utf-8')
->set_output(json_encode(['location' => base_url().'/berkas/news/'.$file['file_name']]))
->_display();
$count = count($file['file_name']);
for ($i=0; $i < $count ; $i++) {
$data2[$i]['id_berita'] = $last;
$data2[$i]['img_name'] = $file['file_name'];
}
$this->text_editor_model->insert_img($data2);
exit;
}
}
my simpan model :
function simpan($data)
{
$this->db->insert('db_news',$data);
$id_berita = $this->db->insert_id();
return $id_berita;
}
if redirect('text_editor'); redirects to another page? then $last = $this->upload_image($ids); will not execute, so you need to call the upload first then redirect
$last = $this->upload_image($ids);
redirect('text_editor');
I am sorry I am editing my question. My real issue is to figure out how to perform a comparison between the $csv_Column_name of fillMapArray function with the value which is stored in the $Csv_header_array in the readRow function. This issue is related to the two csv one table problem since the maps table which stores the csv column name has two csv files loaded into it.
public $table;
public $filename;
public $insert_chunk_size = 500;
public $csv_delimiter = ',';
public $offset_rows = 1;
// Array to store Database column names
public $mapping = [];
public function setTableName($tablename)
{
$this->table = $tablename;
}
public function setFileName($filename)
{
$this->filename = $filename;
}
public function setColumnMapping()
{
//Retrieve the column names of the table
// and store them in the array
$columns = Schema::getColumnListing($this->table);
$i = 0;
while ($i < (sizeof($columns) - 1)) {
array_push($this->mapping, $columns[$i+1]);
$i++;
}
}
public function openCSV($filename)
{
if (!file_exists($filename) || !is_readable($filename)) {
Log::error("CSV insert failed" . $filename . "does not exist or is not readable");
}
$handle = fopen($filename, 'r');
return $handle;
}
public function seedFromCSV($filename, $deliminator = ',')
{
$handle = $this->openCSV($filename);
// CSV doesn't exist or couldn't be read from.
if ( $handle === FALSE )
return [];
$header = NULL;
$row_count = 0;
$data = [];
// Array to store CSV Header column names
$Csv_header_array = [];
$mapping = $this->mapping ?: [];
$offset = $this->offset_rows;
while ( ($row = fgetcsv($handle, 0, $deliminator)) !== FALSE )
{
// Offset the specified number of rows
while ( $offset > 0 )
{
//If the row being read is the first,
//store the CSV header names in the array
$index = 0;
while ($index < sizeof($row)) {
array_push($Csv_header_array, $row[$index]);
$index++;
}
$offset--;
continue 2;
}
// No mapping specified - grab the first CSV row and use it
if ( !$mapping )
{
$mapping = $row;
}
else
{
// Array to store a map of CSV column headers
// to the corresponding values
$source_array = $this->readRow($row, $Csv_header_array);
// Create a map of database column names to
// the corresponding values
$row = $this->fillMapArray($source_array, $mapping);
// insert only non-empty rows from the csv file
if ( !$row )
continue;
$data[$row_count] = $row;
// Chunk size reached, insert
if ( ++$row_count == $this->insert_chunk_size )
{
//var_dump($this->insert($data));
$this->insert($data);
$row_count = 0;
//var_dump($data[0]);
// clear the data array explicitly to
// avoid duplicate inserts
$data = array();
}
}
}
// Insert any leftover rows
if ( count($data) )
$this->insert($data);
fclose($handle);
return $data;
}
public function readRow( array $row, array $Csv_header_array )
{
// Read the values of CSV column headers and map them
// into an array
$source_array = [];
foreach ($Csv_header_array as $index => $csvCol) {
if (!isset($row[$index]) || $row[$index] === '') {
$source_array[$csvCol] = NULL;
}
else {
$source_array[$csvCol] = $row[$index];
}
}
return $source_array;
}
public function fillMapArray($source_array, $mapping) {
$row_values = [];
$columns = Schema::getColumnListing('maps');
$no_of_columns_to_fill = sizeof($source_array);
// Retrieve the CSV column header corresponding to
// the Database column and store in a map
foreach($mapping as $dbCol) {
if ($dbCol === 'year') {
$row_values[$dbCol] = 2014;
} else {
if ($dbCol === 'School_ID') {
$temp1 = DB::Table('schools')->where('Unit_Id', '=',
$source_array['UNITID'])->value('School_ID');
$row_values[$dbCol] = $temp1;
} else {
if ($no_of_columns_to_fill > 0) {
$csv_Column_name = DB::Table('maps')->where($columns[3], '=', $this->table)
->where($columns[1], $dbCol)->value($columns[2]);
if ($csv_Column_name === Null) {
$no_of_columns_to_fill--;
} else {
$row_values[$dbCol] = $source_array[$csv_Column_name];
$no_of_columns_to_fill--;
}
}
}
}
}
//var_dump($row_values);
return $row_values;
}
public function insert( array $seedData )
{
try {
DB::table($this->table)->insert($seedData);
} catch (\Exception $e) {
Log::error("CSV insert failed: " . $e->getMessage() . " - CSV " . $this->filename);
return FALSE;
}
return TRUE;
}
}
You can use Maatwebsite Laravel Excel package to get the CSV data then map it to Eloquent model. Example if your CSV table is users then your model will be User
So you can extract all the data from CSV and then map it to model.
// This array will be created with the help of Laravel-Excel package
$users = array(
array('name'=>'Coder 1', 'rep'=>'4096'),
array('name'=>'Coder 2', 'rep'=>'2048'),
//...
);
// your second CSV file will also perform similar task and map it to same array
$users[] = ['name' => 'Coder 3'];
// Start bulk insert
User::insert($users);
I need to import csv data in database where my Product table have two columns code and price. I am importing data with this script, which find the product code and then update that product price -
function update_price()
{
$this->sma->checkPermissions('csv');
$this->load->helper('security');
$this->form_validation->set_rules('userfile', lang("upload_file"), 'xss_clean');
if ($this->form_validation->run() == true) {
if (isset($_FILES["userfile"])) {
$this->load->library('upload');
$config['upload_path'] = $this->digital_upload_path;
$config['allowed_types'] = 'csv';
$config['max_size'] = $this->allowed_file_size;
$config['overwrite'] = TRUE;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
redirect("products/update_price");
}
$csv = $this->upload->file_name;
$arrResult = array();
$handle = fopen($this->digital_upload_path . $csv, "r");
if ($handle) {
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
$arrResult[] = $row;
}
fclose($handle);
}
$titles = array_shift($arrResult);
$keys = array('code', 'price');
$final = array();
foreach ($arrResult as $key => $value) {
$final[] = array_combine($keys, $value);
}
$rw = 2;
foreach ($final as $csv_pr) {
if (!$this->products_model->getProductByCode(trim($csv_pr['code']))) {
$this->session->set_flashdata('message', lang("check_product_code") . " (" . $csv_pr['code'] . "). " . lang("code_x_exist") . " " . lang("line_no") . " " . $rw);
redirect("product/update_price");
}
$rw++;
}
}
}
if ($this->form_validation->run() == true && !empty($final)) {
$this->products_model->updatePrice($final);
$this->session->set_flashdata('message', lang("price_updated"));
redirect('products');
} else {
$this->data['error'] = (validation_errors() ? validation_errors() : $this->session->flashdata('error'));
$this->data['userfile'] = array('name' => 'userfile',
'id' => 'userfile',
'type' => 'text',
'value' => $this->form_validation->set_value('userfile')
);
$bc = array(array('link' => base_url(), 'page' => lang('home')), array('link' => site_url('products'), 'page' => lang('products')), array('link' => '#', 'page' => lang('update_price_csv')));
$meta = array('page_title' => lang('update_price_csv'), 'bc' => $bc);
$this->page_construct('products/update_price', $meta, $this->data);
}
}
But here our product price update and replace old value , but i want check old value of price and
if old value is greater than uploaded value , then not replaced and
if old value is lower than uploaded value of price then update/replaced that value .
means in all condition our price is always maximum .
how we can do it ??? anyone help please ..
I think you should look inside the updatePrice method and modify a mysql query in it.
Mysql has a proper Update if statement.
My codes multiple image upload and update mysql db but one problem if id=1 It's working multiple image uploading and update.else It's not working and white page.
tables 2
musteri_soru and musteri_cevap
is updating musteri_cevap in colon resim
controller code:
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
if($_FILES){
$dizin= "../upload/form_cevap/";
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++){
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}
Models code :
function duzenle($no,$data)
{
$this->db->update($this->tablo,$data, array('no' => $no));
}
function cevapDuzenle($n,$dat)
{
$data = array('resim' => $dat);
$this->db->update($this->ctablo,$data, array('soru_no' => $n));
}
My Tables
enter link description here
To be honest, I'm not quite sure how your upload was working as the $_FILES array shouldn't be nesting the uploads in the way you've shown above.
I'm not saying this will definitely work but it should do:
function duzenle($no)
{
//I would possible look at using the Form_validation Library here
if (empty($_POST)) {
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no, $arr1);
if (!empty($_FILES)) {
$dizin = "../upload/form_cevap/";
foreach ($_FILES as $name => $file) {
//If there is an error there isn't any reason to try and upload this file
if ($file['error'] !== 0) {
continue;
}
$name = $file['name'];
$isim = md5(uniqid(rand()));
move_uploaded_file($file['tmp_name'], "./$dizin/$isim$name");
$arr['resim'] = $dizin . $isim . $name;
//Not sure what's going on here so I haven't changed it
$approve[] = $arr['resim'];
$it = $approve;
print_r($approve);
foreach ($it as $n => $c):
/* $deneme = $this->form_duzenle_model->cevapDuzenle($n,$c); */
endforeach;
}
}
redirect('form_duzenle/', 'refresh');
}else {
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik' => $veri->baslik,
'veri' => $veri,
'cevap' => $veri2
);
$this->bc->addCrumb($veri->baslik, 'form_duzenle/duzenle/' . $veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle', $data);
}
}
Hope this helps!
Check your for loop,
$dosya_sayi=count($_FILES['cevap']['name']);
for($i=0;$i<=$dosya_sayi;$i++)
for loop condition should be $i < $dosya_sayi as array index always starts from 0.
So correct for loop is
for($i=0;$i<$dosya_sayi;$i++)
I solved the problem.Duzenle codes on change the bottom code.
function duzenle($no)
{
if($_POST)
{
$arr1['baslik'] = $this->input->post('soru');
$this->form_duzenle_model->duzenle($no,$arr1);
$cevaplar = $this->form_duzenle_model->cevapListe($no)->result_array();
if($_FILES){
$dizin= "../upload/form_cevap/";
foreach($cevaplar AS $cevap){
$i = $cevap['no'];
$isim= md5(uniqid(rand()));
if(!empty($_FILES['cevap']['name'][$i])){
move_uploaded_file($_FILES['cevap']['tmp_name'][$i],"./$dizin/$isim{$_FILES['cevap']['name'][$i]}");
$arr['resim']= $dizin.$isim.$_FILES['cevap']['name'][$i];
}
$approve[] = $arr['resim'];
$it = $approve;
$this->form_duzenle_model->cevapDuzenle($i,$arr['resim']);
}
}
redirect('form_duzenle/', 'refresh');
}else{
$this->bc->addCrumb('Düzenle');
$veri = $this->form_duzenle_model->form_duzenleGetir($no)->row();
$veri2 = $this->form_duzenle_model->cevapListe($no)->result();
$data = array(
'baslik'=>$veri->baslik,
'veri' =>$veri,
'cevap' =>$veri2
);
$this->bc->addCrumb($veri->baslik,'form_duzenle/duzenle/'.$veri->no);
$this->layout->view('form_duzenle/form_duzenle_duzenle',$data);
}
}