I'm trying to import an excel file with 15,000 record in a local php and mysql system, but it's always stop inserting in after 3000 records and ignoring the rest of records.
Even in the hosted copy of the system it's insert only 3027 record.
Can I get some help please?
Import csv php script
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;
$config['encrypt_name'] = true;
$config['max_filename'] = 25;
$this->upload->initialize($config);
if (!$this->upload->do_upload()) {
$error = $this->upload->display_errors();
$this->session->set_flashdata('error', $error);
admin_redirect('products/import_csv');
}
$csv = $this->upload->file_name;
$arrResult = [];
$handle = fopen($this->digital_upload_path . $csv, 'r');
if ($handle) {
while (($row = fgetcsv($handle, 15000, ',')) !== false) {
$arrResult[] = $row;
}
fclose($handle);
}
$titles = array_shift($arrResult);
$updated = 0;
$items = [];
foreach ($arrResult as $key => $value) {
$supplier_name = isset($value[24]) ? trim($value[24]) : '';
$supplier = $supplier_name ? $this->products_model->getSupplierByName($supplier_name) : false;
$item = [
'name' => isset($value[0]) ? trim($value[0]) : '',
'code' => isset($value[1]) ? trim($value[1]) : '',
'barcode_symbology' => isset($value[2]) ? mb_strtolower(trim($value[2]), 'UTF-8') : '',
'brand' => isset($value[3]) ? trim($value[3]) : '',
'category_code' => isset($value[4]) ? trim($value[4]) : '',
'unit' => isset($value[5]) ? trim($value[5]) : '',
'sale_unit' => isset($value[6]) ? trim($value[6]) : '',
'purchase_unit' => isset($value[7]) ? trim($value[7]) : '',
'cost' => isset($value[8]) ? trim($value[8]) : '',
'price' => isset($value[9]) ? trim($value[9]) : '',
'alert_quantity' => isset($value[10]) ? trim($value[10]) : '',
'tax_rate' => isset($value[11]) ? trim($value[11]) : '',
'tax_method' => isset($value[12]) ? (trim($value[12]) == 'exclusive' ? 1 : 0) : '',
'image' => isset($value[13]) ? trim($value[13]) : '',
'subcategory_code' => isset($value[14]) ? trim($value[14]) : '',
'variants' => isset($value[15]) ? trim($value[15]) : '',
'cf1' => isset($value[16]) ? trim($value[16]) : '',
'cf2' => isset($value[17]) ? trim($value[17]) : '',
'cf3' => isset($value[18]) ? trim($value[18]) : '',
'cf4' => isset($value[19]) ? trim($value[19]) : '',
'cf5' => isset($value[20]) ? trim($value[20]) : '',
'cf6' => isset($value[21]) ? trim($value[21]) : '',
'hsn_code' => isset($value[22]) ? trim($value[22]) : '',
'second_name' => isset($value[23]) ? trim($value[23]) : '',
'supplier1' => $supplier ? $supplier->id : null,
'supplier1_part_no' => isset($value[25]) ? trim($value[25]) : '',
'supplier1price' => isset($value[26]) ? trim($value[26]) : '',
'slug' => $this->sma->slug($value[0]),
];
if ($catd = $this->products_model->getCategoryByCode($item['category_code'])) {
$tax_details = $this->products_model->getTaxRateByName($item['tax_rate']);
$prsubcat = $this->products_model->getCategoryByCode($item['subcategory_code']);
$brand = $this->products_model->getBrandByName($item['brand']);
$unit = $this->products_model->getUnitByCode($item['unit']);
$base_unit = $unit ? $unit->id : null;
$sale_unit = $base_unit;
$purcahse_unit = $base_unit;
if ($base_unit) {
$units = $this->site->getUnitsByBUID($base_unit);
foreach ($units as $u) {
if ($u->code == $item['sale_unit']) {
$sale_unit = $u->id;
}
if ($u->code == $item['purchase_unit']) {
$purcahse_unit = $u->id;
}
}
} else {
$this->session->set_flashdata('error', lang('check_unit') . ' (' . $item['unit'] . '). ' . lang('unit_code_x_exist') . ' ' . lang('line_no') . ' ' . ($key + 1));
admin_redirect('products/import_csv');
}
unset($item['category_code'], $item['subcategory_code']);
$item['unit'] = $base_unit;
$item['sale_unit'] = $sale_unit;
$item['category_id'] = $catd->id;
$item['purchase_unit'] = $purcahse_unit;
$item['brand'] = $brand ? $brand->id : null;
$item['tax_rate'] = $tax_details ? $tax_details->id : null;
$item['subcategory_id'] = $prsubcat ? $prsubcat->id : null;
if ($product = $this->products_model->getProductByCode($item['code'])) {
if ($product->type == 'standard') {
if ($item['variants']) {
$vs = explode('|', $item['variants']);
foreach ($vs as $v) {
if (!empty(trim($v))) {
$variants[] = ['product_id' => $product->id, 'name' => trim($v)];
}
}
}
unset($item['variants']);
if ($this->products_model->updateProduct($product->id, $item, null, null, null, null, $variants)) {
$updated++;
}
}
$item = false;
}
} else {
$this->session->set_flashdata('error', lang('check_category_code') . ' (' . $item['category_code'] . '). ' . lang('category_code_x_exist') . ' ' . lang('line_no') . ' ' . ($key + 1));
admin_redirect('products/import_csv');
}
if ($item) {
$items[] = $item;
}
}
}
// $this->sma->print_arrays($items);
}
Insert script
public function add_products($products = [])
{
if (!empty($products)) {
foreach ($products as $product) {
$variants = explode('|', $product['variants']);
unset($product['variants']);
if ($this->db->insert('products', $product)) {
$product_id = $this->db->insert_id();
foreach ($variants as $variant) {
if ($variant && trim($variant) != '') {
$vat = ['product_id' => $product_id, 'name' => trim($variant)];
$this->db->insert('product_variants', $vat);
}
}
}
}
return true;
}
return false;
}
I think you're using codeigniter, so i recommend you to use yield (generator in php) and insert_bulk to handle some big data or some huge records to optimize your code and keep your cpu/memory not to leaks or timeout.
Here's some logic :
Import your csv and store it in generator.
Process your titles, key values from csv in one process,DO NOT store it in array variable except your titles only.
Convert the generator to array, and do your another process.
Do your logic to insert the data and Store your inserted data to generator.
Convert the generator to array and insert it using insert_batch function from codeigniter.
Actually you can combine poin 4 to the poin 2 so you have one process do all the logic and the result is the data you want to insert to the database.
Here's my simple code how you implement the logic :
<?php
// I think you're using codeigniter as your framework here, so i recommend you using yield and insert_bulk to insert the data
$filename = "testdata.csv";
$titles = [];
$readcsv = function($filename)use(&$titles){
$keys = ['name','code','barcode_symbology','brand','category_code','unit','sale_unit','purchase_unit','cost','price','alert_quantity','tax_rate','tax_method','image','subcategory_code','variants','cf1','cf2','cf3','cf4','cf5','cf6','hsn_code','second_name','supplier1','supplier1_part_no','supplier1price','slug'];
$handle = fopen($filename,"r");
$first = true;
while (($data = fgetcsv($handle, 15000, ",")) !== FALSE) {
if($first){
$titles = $data;
$first = false;
}else{
if(count($keys) == count($data)){
yield array_combine($keys,$data);
}
}
}
fclose($handle);
};
// Your csv data will be in this variable and your $titles now have value
$yourdata = iterator_to_array($readcsv($filename));
// This function store your inserted data to the yield (generator in php) if the conditions true
$list_insert_data = function($yourdata){
// Loop your csv data and do your logic here...
$break = false;
$cnt = 1;
foreach($yourdata as $v){
if(!empty($v) && !$break){
yield $v;
}
// Just simple logic to store 3 records from the csv
if($cnt == 3){
$break = true;
}else if($break){
break;
}
$cnt++;
}
};
// This variable contains 3 array from the csv data
$inserted = iterator_to_array($list_insert_data($yourdata));
// Then insert the data to the database.
$this->db->insert_batch('product_variants', $inserted);
UPDATED:
If you're using mysql, you need to check your max_allowed_packet and check it in your mysql SHOW VARIABLES WHERE Variable_name LIKE '%max_allowed_packet%' and increase or double the value.
Change in the my.ini file by including the single line under [mysqld] or [client] section in your file:
max_allowed_packet=1024M
then restart the MySQL service and you are done. Hope this simple logic help you out of trouble.
You need to change the max_execution_time on php.ini
max_execution_time = 5000
Or on top of your script, add the following line.
ini_set('max_execution_time', 5000);
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 was working on another person's code and when I deployed the laravel app the login page works but when I input the testing credentials it spits out this error
Trying to get property 'id' of non-object
in helpers.php line 159
at HandleExceptions->handleError(8, 'Trying to get property \'id\' of non-object', '/var/www/html/first-project/app/Helpers/helpers.php', 159, array('fields' => object(Collection), 'fieldsValues' => object(Collection), 'htmlFields' => array(), 'startSeparator' => '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">', 'endSeparator' => '</div>', 'field' => object(CustomField), 'dynamicVars' => array('$RANDOM_VARIABLE$' => 'var15931958241638660037ble', '$FIELD_NAME$' => 'phone', '$DISABLED$' => '', '$REQUIRED$' => '"required" => "required",', '$MODEL_NAME_SNAKE$' => 'user', '$FIELD_VALUE$' => '\'+136 226 5660\'', '$INPUT_ARR_SELECTED$' => '+136 226 5660'), 'gf' => object(GeneratorField), 'value' => object(CustomFieldValue)))
in helpers.php line 159
The actual function referred to is the following
function generateCustomField($fields, $fieldsValues = null)
{
$htmlFields = [];
$startSeparator = '<div style="flex: 50%;max-width: 50%;padding: 0 4px;" class="column">';
$endSeparator = '</div>';
foreach ($fields as $field) {
$dynamicVars = [
'$RANDOM_VARIABLE$' => 'var' . time() . rand() . 'ble',
'$FIELD_NAME$' => $field->name,
'$DISABLED$' => $field->disabled === true ? '"disabled" => "disabled",' : '',
'$REQUIRED$' => $field->required === true ? '"required" => "required",' : '',
'$MODEL_NAME_SNAKE$' => getOnlyClassName($field->custom_field_model),
'$FIELD_VALUE$' => 'null',
'$INPUT_ARR_SELECTED$' => '[]',
];
$gf = new GeneratorField();
if ($fieldsValues) {
foreach ($fieldsValues as $value) {
if ($field->id === $value->customField->id) {
$dynamicVars['$INPUT_ARR_SELECTED$'] = $value->value ? $value->value : '[]';
$dynamicVars['$FIELD_VALUE$'] = '\'' . addslashes($value->value) . '\'';
$gf->validations[] = $value->value;
continue;
}
}
}
// dd($gf->validations);
$gf->htmlType = $field['type'];
$gf->htmlValues = $field['values'];
$gf->dbInput = '';
if ($field['type'] === 'selects') {
$gf->htmlType = 'select';
$gf->dbInput = 'hidden,mtm';
}
$fieldTemplate = HTMLFieldGenerator::generateCustomFieldHTML($gf, config('infyom.laravel_generator.templates', 'adminlte-templates'));
if (!empty($fieldTemplate)) {
foreach ($dynamicVars as $variable => $value) {
$fieldTemplate = str_replace($variable, $value, $fieldTemplate);
}
$htmlFields[] = $fieldTemplate;
}
// dd($fieldTemplate);
}
foreach ($htmlFields as $index => $field) {
if (round(count($htmlFields) / 2) == $index + 1) {
$htmlFields[$index] = $htmlFields[$index] . "\n" . $endSeparator . "\n" . $startSeparator;
}
}
$htmlFieldsString = implode("\n\n", $htmlFields);
$htmlFieldsString = $startSeparator . "\n" . $htmlFieldsString . "\n" . $endSeparator;
// dd($htmlFieldsString);
$renderedHtml = "";
try {
$renderedHtml = render(Blade::compileString($htmlFieldsString));
// dd($renderedHtml);
} catch (FatalThrowableError $e) {
}
return $renderedHtml;
}
its usage is as follows in the controllers. It is used many times in almost all controllers for example in the UserController.php file I think this is the calling method. I am not that well versed in laravel sorry for any noob mistakes in advance.
public function profile()
{
$user = $this->userRepository->findWithoutFail(auth()->id());
unset($user->password);
$customFields = false;
$role = $this->roleRepository->pluck('name', 'name');
$rolesSelected = $user->getRoleNames()->toArray();
$customFieldsValues = $user->customFieldsValues()->with('customField')->get();
$hasCustomField = in_array($this->userRepository->model(), setting('custom_field_models', []));
if ($hasCustomField) {
$customFields = $this->customFieldRepository->findByField('custom_field_model', $this->userRepository->model());
$customFields = generateCustomField($customFields, $customFieldsValues);
}
return view('settings.users.profile', compact(['user', 'role', 'rolesSelected', 'customFields', 'customFieldsValues']));
}
You have to change this line
From
$user = $this->userRepository->findWithoutFail(auth()->id());
To
$user = $this->userRepository->findWithoutFail(auth()->user()->id());
My first guess, change this $user = $this->userRepository->findWithoutFail(auth()->id()); to $user = $this->userRepository->findWithoutFail(auth()->user()->id);
Added auth()->user()->id;
Please help me about this one.
i have a table name 'aptimportdata' and 'aptimportdataaddress'.
the code below is a function for import a microsoft excel data to the website.
i want to send a data from table aptimportdata to aptimportdataaddress, but i don't know how, because in the excel file, there are 2 home address columns for one person, one with the columns name homeaddress1 to 4, and the other one is altaddress1 to 4, the "altaddress" is created for a person who have a home address more than 1.
now when i import the data from the website, the data is sent to the aptimportdata table and it doesn't have a problem when i upload the file from the website, but when i change the "altaddress" data destination table to aptimportdataaddress table, the website just give me an endless loading without a success report.
i already make a column for the "altaddress" in aptimportdataaddress table, but i cant find a solution how to make the "altaddress" data go to aptimportaddress table and its just the "altaddress" column data that i want to put at the aptimportdataaddress table.
if you need a screenshot for the what the table looks like, i'll send it.
this is my code :
= 5.3.3
* #copyright 2014 Sereware
* #developer Yudha Tama Aditiyara
* #application controller/apartement
*/
class import extends Controller
{
protected $_models = array('apartement/import/m_import');
public function dataexcel(){
$config['ajax_upload_dataexcel'] = site_url('apartement/import/ajax_upload_dataexcel');
$config['ajax_process_dataexcel'] = site_url('apartement/import/ajax_process_dataexcel/'.$this->d_page->page('noid'));
$this->load->view('apartement/import/dataexcel',$config);
}
public function ajax_upload_dataexcel(){
$id = str_replace('.','',microtime(true));
$upload = new Sereware\ExcelUpload(array('upload_dir' => SYSPATH.'files/'),false);
$upload->hasNormalFilename = true;
$this->d_page->obstart();
$upload->post();
ob_flush();
}
protected $apttower = array(
'h' => 1,'s'=>2,'y'=>3,'p'=>4
);
#{{{
protected function get_dataexcel(){
if (!isset($_REQUEST['file']) || !trim($_REQUEST['file']))return;
$file = $_REQUEST['file'];
$file = SYSPATH."files/" . $file . (pathinfo($file,PATHINFO_EXTENSION) !== 'xls' ? '.xls' : '');
if (!file_exists($file)) return;
$excel = new Sereware\Excel($file);
$data = $excel->getCells(0);
return $data;
}
protected function matcher_excelfield($dataexcelfields, $appimportdetails){
$fieldnames = array();
foreach($dataexcelfields as $indexField => $dataexcelfield) {
$dataexcelfield = strtolower(preg_replace('#[\n\r]#','',trim($dataexcelfield)));
if (isset($appimportdetails[$dataexcelfield])) {
$destfield = preg_replace('#[\n\r]#','',$appimportdetails[$dataexcelfield]->destfield);
$desttypefield = (int)$appimportdetails[$dataexcelfield]->desttypefield;
$isnormalized = $appimportdetails[$dataexcelfield]->isnormalized;
$defaultvalue = $appimportdetails[$dataexcelfield]->defaultvalue;
$appimportdetail = $appimportdetails[$dataexcelfield];
$appimportdetail_desttables = array_filter(explode(';',$appimportdetail->desttable));
foreach($appimportdetail_desttables as $tablename) {
$fieldnames[$tablename][$indexField] = array(
'destfield' => $destfield,
'desttypefield' => $desttypefield,
'isnormalized' => $isnormalized,
'defaultvalue' => $defaultvalue
);
}
}
}
return $fieldnames;
}
protected function normalize_dataexcel($destfield,$value){
$value = trim($value);
switch($destfield) {
case 25:
$value = str_replace('%','',$value);
break;
case 11:
if ($value){
$value = strtotime(str_replace('/', '-',(string)$value));
$value = date('Y-m-d',$value);
} else {
$value = null;
}
break;
case 34:
if (!$value) {
$value = -1;
} else {
$value = strtolower($value) === 'ok' ? 1 : 0;
}
break;
}
return $value;
}
public function ajax_process_dataexcel($idpage){
$appimport = $this->m_import->get_appimport();
$appimportdetails = $this->m_import->get_appimportdetails($appimport->idconnection,$appimport->noid);
$aptimportdatas = $this->m_import->get_aptimportdatas($appimport->idconnection);
$newid_aptimportdata = $this->m_import->get_maxid_aptimportdata();
$aptsyarats = $this->m_import->data_aptsyarats();
$aptdatabap = $this->m_import->data_aptbap();
$dataexcel = $this->get_dataexcel();
$dataexcelfields = $this->matcher_excelfield(array_shift($dataexcel),$appimportdetails);
$insert_data = array();
$update_data = array();
$insert_data_aptunitroom = array();
$insert_data_aptimportdataaddress = array();
$insert_data_aptunitroomsyarat = array();
$insert_data_aptdatabap = array();
$datamcarduser = $this->d_page->d_login->get_datamcarduser();
// var_dump(json_encode($dataexcelfields));
// exit();
foreach($dataexcel as $data) {
foreach($dataexcelfields as $tablename => $fieldnames) {
##-1
##-build data per-row
$ndata = array();
$ready = true;
$ndata['idcreate'] = $datamcarduser->noid;
$ndata['idupdate'] = $datamcarduser->noid;
$ndata['docreate'] = date('Y-m-d H:i:s');
$ndata['lastupdate'] = date('Y-m-d H:i:s');
foreach($fieldnames as $indexFieldExcel => $datafields) {
$fieldname = $datafields['destfield'];
$isnormalized = intval($datafields['isnormalized']);
$defaultvalue = $datafields['defaultvalue'];
$desttypefield = $datafields['desttypefield'];
if (!$isnormalized) {
$defaultvalue = $data[$indexFieldExcel];
}
$ndata[$fieldname] = $this->normalize_dataexcel($desttypefield,$defaultvalue);
}
##-2
if (isset($ndata['lotno']) && isset($aptimportdatas[$ndata['lotno']])) {
$metadata = $aptimportdatas[$ndata['lotno']];
if ($tablename === 'aptimportdata') {
$update_data[$tablename][$metadata['metadata']->noid] = $ndata;
// if (!empty($ndata['ppjbdate'])) {
// }
$update_data['aptunitroom'][$metadata['metadata']->noid] = array(
'statuslegal' => empty($ndata['ppjbdate']) ? 0 : 1,
'statusproject' => $ndata['isreadytoho']
);
$mimportlog_r = array_merge(array("noid" => $metadata['metadata']->noid), $ndata);
$insert_data['mimportlog'][] = $mimportlog_r;
continue;
}
$matchers = $metadata['matchers'];
$extrafields = $metadata['extrafields'];
if (isset($matchers[$tablename])) {
foreach($matchers[$tablename] as $_fieldname => $value) {
if ($value === (int)$ndata[$_fieldname]) {
$ready = false;
break;
}
}
}
##-
if ($ready) {
if (isset($extrafields[$tablename])) {
foreach($extrafields[$tablename] as $__fieldname => $_value) {
$ndata[$__fieldname] = $_value;
}
}
}
}
##-3
if ($ready) {
$lotno = false;
if ($tablename === 'aptimportdata') {
$lotno = $ndata['lotno'];
$ndata['noid'] = $newid_aptimportdata;
$insert_data_aptunitroom[] = array(
'noid' => $newid_aptimportdata,
'statusproject' => $ndata['isreadytoho'],
'statuslegal' => empty($ndata['ppjbdate']) ? -1 : 1
);
$insert_data_aptimportdataaddress[] = array(
'noid' => $newid_aptimportdata
);
foreach($aptsyarats as $key => &$aptsyaratdata) {
$aptsyaratdata = (array)$aptsyaratdata;
$aptsyaratdata['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptunitroomsyarat[] = $aptsyaratdata;
}
foreach($aptdatabap as $key => $data){
$data = (array)$data;
$data['idaptunitroom'] = $newid_aptimportdata;
$insert_data_aptdatabap[] = $data;
}
$newid_aptimportdata++;
}
if ($lotno !== false) {
$insert_data[$tablename][$lotno] = $ndata;
} else {
$insert_data[$tablename][] = $ndata;
}
}
}
}
$real_insert_data = array();
if (isset($insert_data['aptimportdata'])) {
$_aptimportdata = $insert_data['aptimportdata'];
$real_insert_data['aptimportdata'] = array_values($_aptimportdata);
$real_insert_data['mimportlog'] = array_values($_aptimportdata);
foreach($insert_data as $tablename => $datas) {
if ($tablename !== 'aptimportdata' && $tablename !== 'aptunitroom') {
$real_insert_data[$tablename] = array();
foreach($datas as $key => $data) {
if ((!isset($data['idaptunitroom']) || intval($data['idaptunitroom']) === 0) || $_aptimportdata[$data['lotno']]) {
$data['idaptunitroom'] = $_aptimportdata[$data['lotno']]['noid'];
}
$real_insert_data[$tablename][$key] = $data;
}
}
}
} else {
$real_insert_data = $insert_data;
}
if (!empty($insert_data_aptunitroom)) {
$real_insert_data['aptunitroom'] = $insert_data_aptunitroom;
$real_insert_data['aptimportdataaddress'] = $insert_data_aptimportdataaddress;
}
if (!empty($insert_data_aptunitroomsyarat)) {
$real_insert_data['aptunitroomsyarat'] = $insert_data_aptunitroomsyarat;
$real_insert_data['aptunitroomdatabap'] = $insert_data_aptdatabap;
}
$gagal = array();
$dbase = new Sereware\Query($appimport->idconnection);
// var_dump(json_encode($real_insert_data));
// exit();
if (!empty($real_insert_data)) {
foreach($real_insert_data as $tablename => $data) {
try {
$db = $dbase->table($tablename);
$db->insert($data);
}catch(Exception $e){
$gagal['insert'][$tablename] = $e->getMessage();
}
}
}
if (!empty($update_data)) {
foreach($update_data as $tablename => $datas) {
foreach($datas as $noid => $data) {
try {
$db = $dbase->table($tablename);
$db->where('noid','=',$noid);
$db->update($data);
}catch(Exception $e){
$gagal['update'][$tablename] = $e->getMessage();
}
}
}
}
ob_start();
echo !count($gagal);
ob_flush();
}
#}}}
}
i'm still using localhost, and sublime text.
the "altaddress" and "homeaddress" are not inside the code, because it's a columns in the table. you can only find a table name on the code.
my question is how can i make the "altaddress" data from aptimportdata table go to aptimportdataaddress table, i dont't want the altaddress go to aptimportdata table, i just want the data get to aptimportdataaddress.
I'm currently implementing smartrecruiter api in my project. I'm using two endpoints namely /jobs-list and /job-details. The problem is that every time I'm extracting the details in the second endpoint which is the /job-details, the execution time is so slow.
Here's what I've done so far:
function getContext()
{
$opts = array(
'http'=> array(
'method' => 'GET',
'header' => 'X-SmartToken: xxxxxxxxxxxxxxxxx'
)
);
return $context = stream_context_create($opts);
}
function getSmartRecruitmentJob($city, $department)
{
$tmp = array();
$results= array();
$limit = 100; //max limit for smartrecruiter api is 100
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs?limit='.$limit.'&city='.$city.'&department='.$department, false, $this->getContext());
$lists= json_decode($file, true);
foreach($lists['content'] as $key => $list)
{
if ($list['status'] == 'SOURCING' || $list['status'] == 'INTERVIEW' || $list['status'] == 'OFFER')
{
$results['id'] = $list['id'];
$tmp[] = $this->getSmartRecruitmentJobDetails($results['id']);
}
}
return $tmp;
}
function getSmartRecruitmentJobDetails($id)
{
$results = array();
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}
Solved it by caching the function for extracting the data:
function getCache()
{
if ($this->cache === null)
{
$cache = \Zend\Cache\StorageFactory::factory(
array(
'adapter' => array(
'name' => 'filesystem',
'options' => array(
'ttl' => 3600 * 7, // 7 hours
'namespace' => 'some-namespace',
'cache_dir' => 'your/cache/directory'
),
),
'plugins' => array(
'clear_expired_by_factor' => array('clearing_factor' => 10),
),
)
);
$this->cache = $cache;
}
return $this->cache;
}
function getSmartRecruitmentJobDetails($id)
{
$cache = $this->getCache();
$key = md5('https://api.smartrecruiters.com/jobs/'.$id);
$lists = unserialize($cache->getItem($key, $success));
$results = array();
if($success && $lists)
{
header('Debug-cache-recruit: true');
}
else
{
header('Debug-cache-recruit: false');
// Open the file using the HTTP headers set above
$file = file_get_contents('https://api.smartrecruiters.com/jobs/'.$id, false, $this->getContext());
$lists= json_decode($file, true);
$cache->addItem($key, serialize($lists));
}
$results['title'] = isset($lists['title']) ? $lists['title'] : null;
$results['department_label'] = isset($lists['department']['label']) ? $lists['department']['label'] : null;
$results['country'] = isset($lists['location']['country']) ? $lists['location']['country'] : null;
$results['country_code'] = isset($lists['location']['countryCode']) ? $lists['location']['countryCode'] : null;
$results['city'] = isset($lists['location']['city']) ? $lists['location']['city'] : null;
$results['url'] = isset($lists['actions']['applyOnWeb']['url']) ? $lists['actions']['applyOnWeb']['url'] : null;
return $results;
}
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.