I have a script for inserting a product custom options in Magento. Its working fine for single custom option, if there are multiple custom options for a single product then it insert only single custom option and discard others.
<?php
// Report all PHP errors (see changelog)
error_reporting(E_ALL);
ini_set("display_errors", 1);
// Same as error_reporting(E_ALL);
ini_set('error_reporting', E_ALL);
// Include Magento application
require_once ( "../app/Mage.php" );
umask(0);
// Initialize Magento
Mage::app("default");
$start = 0;
$totalno =1000;
$row = 0;
$sku = 0;
$baseRowoption = array();
$myarrayoption = array();
if (($handle = fopen("custom_option-final.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle,",")) !== FALSE) {
$num = count($data);
for ($c=0; $c < $num; $c++) {
if($row == 0){
$baseRowoption[$c]=$data[$c];
}else{
if($c==0){
$sku=$data[$c];
}
$myarrayoption[$sku][$row][$baseRowoption[$c]]=$data[$c];
}
}
$row++;
if($row > $totalno){
break;
}
}
fclose($handle);
}
$myarrayoptionfinal = array();
foreach($myarrayoption as $key=>$myarrayoption1){
//if($key != "smartek-rx3044"){ break; }
foreach($myarrayoption1 as $myarrayoption11){
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['input_type'] = $myarrayoption11['input_type'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['required'] = $myarrayoption11['required'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['sort_order'] = $myarrayoption11['sort_order'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_title'][] = $myarrayoption11['row_title'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_price'][] = $myarrayoption11['row_price'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_price_type'][] = $myarrayoption11['row_price_type'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_sku'][] = $myarrayoption11['row_sku'];
$myarrayoptionfinal[$key][$myarrayoption11['option_title']]['row_sort_order'][] = $myarrayoption11['row_sort_order'];
}
}
echo "<pre>";
echo "total No : ".count($myarrayoptionfinal);
echo "<br />";
//print_r($myarrayoptionfinal);
$i=0;
foreach($myarrayoptionfinal as $keys=>$myarrayoptionfinal1){
if($i<$start){
$i++; continue;
}
echo "<br />".$i."--->";
$i++;
echo $keys."--->";
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$keys);
if($product){
foreach ($product->getProductOptionsCollection() as $option)
{
$optionsData = $option->getData();
$optionsData['is_delete'] = 1;
$product->setProductOptions(array($option->getId() => $optionsData));
$product->setCanSaveCustomOptions(true);
$product->save();
}}else{
continue;
}
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$keys);
print_r($product->getData("entity_id"));
foreach($myarrayoptionfinal1 as $keysub=>$myarrayoptionfinal11){
$subarray = array();
foreach($myarrayoptionfinal11['row_title'] as $keysub1=>$myarrayoptionfinal111){
$subarray[]=array(
'is_delete' => 0,
'title' => $myarrayoptionfinal111,
'price_type' => $myarrayoptionfinal11['row_price_type'][$keysub1],
'price' => $myarrayoptionfinal11['row_price'][$keysub1],
'sku' => $keys.'_'.$myarrayoptionfinal11['row_sku'][$keysub1],
'sort_order' => $myarrayoptionfinal11['row_sort_order'][$keysub1],
'option_type_id'=> -1,
);
}
$required = false;
if($myarrayoptionfinal11["required"] == 1) $required = true;
$opt = array(
'is_delete' => 0,
'is_require' => $required,
'previous_group' => '',
'title' => $keysub,
'type' => $myarrayoptionfinal11["input_type"],
'price_type' => '',
'price' => '',
'sort_order' => $myarrayoptionfinal11["sort_order"],
/** array of values for this option **/
'values' => $subarray,
);
}
try {
//print_r($opt);
$option = Mage::getModel('catalog/product_option')
->setProduct($product)
->addOption($opt)
->saveOptions();
$product->setHasOptions(1);
$product->save();
}
catch (Exception $e) {
echo 'Caught exception 2: '.$e->getMessage()."\n";
continue;
}
}
Add custom option to multiple products is quite difficult because there are multiple type custom option in magento like (dropdown, text etc.) also you will found in each custom option multiple values which you need to handle.
http://www.magentocommerce.com/magento-connect/custom-option-manger.html
This extension provides exact functionality multiple custom options for multiple products.
Related
I have a simple question that needs to get an element when selecting that reference ID by an input form. I used the following code to do that.
$id2=$locationProducts[0]->inventory_update_stock_details_id;
But this code outs only the first element always. AS an exmple inventory_update_stock_details_id=36, inventory_update_stock_details_id=36, inventory_update_stock_details_id=36 and so on.
But I needs to select as inventory_update_stock_details_id=35, inventory_update_stock_details_id=345, inventory_update_stock_details_id=2 like that.
inventory_update_stock_details_id included ids as 1,2,3,4,5,......1000
The model as follows :
function getInventoryLocationProducts()
{
$this->db->select("*");
$this->db->from('store_inventory_update_stock_details');
$this->db->join('store_inventory_item', 'store_inventory_item.inventory_item_id=store_inventory_update_stock_details.inventory','left');
$this->db->join('store_inventory_location_update', 'store_inventory_location_update.inventory_update_stock_id=store_inventory_update_stock_details.inventory_update_stock_id','left');
$this->db->join('store_inventory_update_stock', 'store_inventory_update_stock.inventory_update_stock_id=store_inventory_location_update.inventory_update_stock_id','left');
$this->db->where('store_inventory_item.status=1');
$this->db->where('store_inventory_update_stock_details.serial_no NOT IN (select serial_no from store_inventory_location_update)');
$q = $this->db->get_where();
if ($q->num_rows() > 0) {
return $q->result();
}
return FALSE;
}
Controller
public function addInventoryLocation()
{
$this->checkPermissions('add', 'inventoryLocation');
$bc = array(array('link' => '#', 'page' => 'Inventory Locations'));
$meta = array('page_title' => 'Inventory Locations', 'bc' => $bc);
$this->data['branch'] = $this->Item_model->getBranch();
$this->data['office'] = $this->Item_model->getOffice();
$locationProducts = $this->Item_model->getInventoryLocationProducts();
$this->data['locationProducts'] = $locationProducts;
$this->data['auto_loc_no'] = $this->Item_model->generate_inv_loc_ref();
$count = $this->input->post('i');
$str = $this->input->post('auto_loc_no');
$auto_loc = preg_replace("/[^0-9]{1,4}/", '', $str);
$this->form_validation->set_rules('branch', 'Branch', 'required');
if ($this->form_validation->run() == true) {
$stock = array(
'office_id' => $this->input->post('office'),
'branch' => $this->input->post('branch'),
'l_date' => $this->input->post('l_date'),
'is_order_no' => $this->input->post('is_order_no'),
'loc_no' => $this->input->post('auto_loc_no'),
'auto_loc_no' => $auto_loc,
'user' => ucfirst($this->session->userdata('name')),
'order_status' => 'locate',
'status' => 1
);
$id = $this->Item_model->addInventoryLocation($stock);
}
$id2=$locationProducts[0]->inventory_update_stock_details_id;
dd($id2);
if ($this->form_validation->run() == true && $id2 != 0) {
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[$x]['inventory_update_stock_id'] = $id2;
$details[$x]['inventory'] = $this->input->post('inventory' . $x);
$details[$x]['serial_no'] = $this->input->post('serial_no' . $x);
$details[$x]['item_code'] = $this->input->post('item_code' . $x);
$details[$x]['officer'] = $this->input->post('officer' . $x);
$details[$x]['qty'] = 1;
$details[$x]['status'] = 1;
$details[$x]['branch'] = $this->input->post('branch');
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
} else {
$this->session->set_flashdata('error', validation_errors());
$this->render('item/addInventoryLocation', $meta, $this->data);
}
}
View
<td style="width: 30%">
<input type="hidden" name="i" id="i" value="0">
<select name="inventory0" id="inventory0" class="form-control select2 inventory-select" required>
<option value=""></option>
<?php
if (!empty($locationProducts)) {
foreach ($locationProducts as $row) {
echo "<option value='".$row->inventory_update_stock_details_id."'> $row->inventory_update_stock_details_id - $row->inventory_item_name</option>";
?>
<?php
}
}
?>
</select>
</td>
What can modify my code line to do that. Can anyone help me ?
I'm not entirely sure what the intended logic is, but I think what you want is to add the InventoryLocationDetails to all InventoryLocationProducts.
If that is correct, you could perhaps do something like this:
if ($this->form_validation->run() == true) {
$details = [];
foreach ($locationProducts as $locationProduct) {
$id2 = $locationProduct->inventory_update_stock_details_id;
$count = $this->input->post('i');
for ($x = 0; $x <= $count; $x++) {
$details[] = [
'inventory_update_stock_id' => $id2,
'inventory' => $this->input->post('inventory' . $x),
'serial_no' => $this->input->post('serial_no' . $x),
'item_code' => $this->input->post('item_code' . $x),
'officer' => $this->input->post('officer' . $x);
'qty' => 1,
'status' => 1,
'branch' => $this->input->post('branch'),
];
}
}
if ($this->Item_model->addInventoryLocationDetails($details)) {
echo("<meta http-equiv='refresh' content='1'>");
$this->session->set_flashdata('message', 'Successfully Added ..!!');
redirect('item/addInventoryLocation');
}
}
This assumes that $locationProducts contains only those products that actually need to be updated. If you need to only update some of them, you can add the logic to determine which product to update inside the foreach loop.
I want to fetch the product details that are added to cart, on page load in checkout page.
As we know in checkout page there is generally six Steps to place order, where each step's information is in
<div class="panel-body"></div>
which remains empty until we reached to that step.
so, product details is under the last step(6th) to be fetched.
But i want to fetch the products details which i will show on right side in
<div classs="col-md-4"> </div>
Ideally you're going to want to create an OCMOD for this but that is outside of the scope of answering this question.
Since you're looking at inserting the contents of the "cart" into the page, you'll need to copy the controller logic from the cart "module" controller catalog/controller/common/cart.php and the markup from the view catalog/view/theme/default/template/common/cart.tpl (change according to your template).
Grab these lines from inside the controller file (Public function index()):
$this->load->language('common/cart');
// Totals
$this->load->model('extension/extension');
$totals = array();
$taxes = $this->cart->getTaxes();
$total = 0;
// Because __call can not keep var references so we put them into an array.
$total_data = array(
'totals' => &$totals,
'taxes' => &$taxes,
'total' => &$total
);
// Display prices
if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
$sort_order = array();
$results = $this->model_extension_extension->getExtensions('total');
foreach ($results as $key => $value) {
$sort_order[$key] = $this->config->get($value['code'] . '_sort_order');
}
array_multisort($sort_order, SORT_ASC, $results);
foreach ($results as $result) {
if ($this->config->get($result['code'] . '_status')) {
$this->load->model('extension/total/' . $result['code']);
// We have to put the totals in an array so that they pass by reference.
$this->{'model_extension_total_' . $result['code']}->getTotal($total_data);
}
}
$sort_order = array();
foreach ($totals as $key => $value) {
$sort_order[$key] = $value['sort_order'];
}
array_multisort($sort_order, SORT_ASC, $totals);
}
$data['text_empty'] = $this->language->get('text_empty');
$data['text_cart'] = $this->language->get('text_cart');
$data['text_checkout'] = $this->language->get('text_checkout');
$data['text_recurring'] = $this->language->get('text_recurring');
$data['text_items'] = sprintf($this->language->get('text_items'), $this->cart->countProducts() + (isset($this->session->data['vouchers']) ? count($this->session->data['vouchers']) : 0), $this->currency->format($total, $this->session->data['currency']));
$data['text_loading'] = $this->language->get('text_loading');
$data['button_remove'] = $this->language->get('button_remove');
$this->load->model('tool/image');
$this->load->model('tool/upload');
$data['products'] = array();
foreach ($this->cart->getProducts() as $product) {
if ($product['image']) {
$image = $this->model_tool_image->resize($product['image'], $this->config->get($this->config->get('config_theme') . '_image_cart_width'), $this->config->get($this->config->get('config_theme') . '_image_cart_height'));
} else {
$image = '';
}
$option_data = array();
foreach ($product['option'] as $option) {
if ($option['type'] != 'file') {
$value = $option['value'];
} else {
$upload_info = $this->model_tool_upload->getUploadByCode($option['value']);
if ($upload_info) {
$value = $upload_info['name'];
} else {
$value = '';
}
}
$option_data[] = array(
'name' => $option['name'],
'value' => (utf8_strlen($value) > 20 ? utf8_substr($value, 0, 20) . '..' : $value),
'type' => $option['type']
);
}
// Display prices
if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
$price = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')), $this->session->data['currency']);
} else {
$price = false;
}
// Display prices
if ($this->customer->isLogged() || !$this->config->get('config_customer_price')) {
$total = $this->currency->format($this->tax->calculate($product['price'], $product['tax_class_id'], $this->config->get('config_tax')) * $product['quantity'], $this->session->data['currency']);
} else {
$total = false;
}
$data['products'][] = array(
'cart_id' => $product['cart_id'],
'thumb' => $image,
'name' => $product['name'],
'model' => $product['model'],
'option' => $option_data,
'recurring' => ($product['recurring'] ? $product['recurring']['name'] : ''),
'quantity' => $product['quantity'],
'price' => $price,
'total' => $total,
'href' => $this->url->link('product/product', 'product_id=' . $product['product_id'])
);
}
// Gift Voucher
$data['vouchers'] = array();
if (!empty($this->session->data['vouchers'])) {
foreach ($this->session->data['vouchers'] as $key => $voucher) {
$data['vouchers'][] = array(
'key' => $key,
'description' => $voucher['description'],
'amount' => $this->currency->format($voucher['amount'], $this->session->data['currency'])
);
}
}
$data['totals'] = array();
foreach ($totals as $total) {
$data['totals'][] = array(
'title' => $total['title'],
'text' => $this->currency->format($total['value'], $this->session->data['currency']),
);
}
Create a new file in the catalog/controller/common/ folder, call it products.php and use the following structure:
<?php
class ControllerCommonProducts extends Controller {
public function index(){
//placeholder
return $data;
}
}
Paste the copied text it into the new file replacing the //placeholder line.
Edit the catalog/controller/checkout/checkout.php file, insert this line to load the data from the controller we have just created into the checkout page view:
$data['products_view'] = $this->load->controller('common/products'); insert it just above this line:
$this->response->setOutput($this->load->view('checkout/checkout', $data));
Now edit the view catalog/view/theme/default/template/checkout/checkout.tpl you will now have a new array products_view that you can use on the view as you need. Start with a var_dump of the array to see what data you have to work with.
Summary: What we've done here is replicate an existing controller (1, 2 & 3) - excluding the controller logic where it loads the data into a view. We then edited the controller's index action (3) of the page we're displaying data on and loaded the new controller (4) into an array to be used on the front end view (5).
I'm trying to create an order using the web service on another web page i have. I'm running the latest version of PrestaShop 1.7. It's really basic, just entering ID of product and quantity. This is my first serious task and i'm struggling to make this work, which it still doesn't. The code i will soon show can create a cart, but it can not create the order for some reason.
Code:
try {
/*
Creating new cart
*/
$xml = $webService->get( array( 'url' => PS_SHOP_PATH .'/api/carts?schema=blank' ) );
// Required
$xml->cart->id_currency = 1;
$xml->cart->id_lang = 1;
foreach($_SESSION['vezimas'] as $i => $vezimas) {
$xml->cart->associations->cart_rows->cart_row[$i]->id_product = $vezimas['product_id'];
$xml->cart->associations->cart_rows->cart_row[$i]->quantity = $vezimas['qty'];
}
// Adding the new cart
$opt = array( 'resource' => 'carts' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
$id_cart = $xml->cart->id;
/*
Creating Order
*/
// Getting the structure of an order
$xml = $webService->get(array('url' => PS_SHOP_PATH .'/api/orders/?schema=blank'));
// Required
$xml->order->id_address_delivery = 6; // Customer address
$xml->order->id_address_invoice = 6;
$xml->order->id_cart = $id_cart;
$xml->order->id_currency = 1;
$xml->order->id_lang = 1;
$xml->order->id_customer = 2;
$xml->order->id_carrier = 1;
$xml->order->module = 'ps_checkpayment';
$xml->order->payment = 'Payments by check';
$xml->order->total_paid = 0;
$xml->order->total_paid_real = 0;
$xml->order->total_products = $_SESSION['prekesNum'];
$xml->order->total_products_wt = 0;
$xml->order->conversion_rate = 1;
// Others
$xml->order->valid = 1;
// Order Row. Required
foreach($_SESSION['vezimas'] as $i => $vezimas) {
$xml->order->associations->order_rows->order_row[0]->product_id = $vezimas['product_id'];
$xml->order->associations->order_rows->order_row[0]->product_quantity = $vezimas['qty'];
}
// Creating the order
$opt = array( 'resource' => 'orders' );
$opt['postXml'] = $xml->asXML();
$xml = $webService->add( $opt );
$id_order = $xml->order->id;
} catch (PrestaShopWebserviceException $e) {
// Here we are dealing with errors
$trace = $e->getTrace();
if ($trace[0]['args'][0] == 404) echo 'Bad ID';
else if ($trace[0]['args'][0] == 401) echo 'Bad auth key';
else echo 'Other error<br />'.$e->getMessage();
}
I get a fatal error in Debug, and this on the page:
Other error
HTTP XML response is not parsable: array ( 0 => LibXMLError::__set_state(array( 'level' => 3, 'code' => 4, 'column' => 1, 'message' => 'Start tag expected, \'<\' not found ', 'file' => '', 'line' => 1, )), )
Added some more field and a secure key to my cart code then it worked fine.
I have these following functions.
public function importExcelFile(){
$file = $_FILES['file']['tmp_name'];
$data = extract_excel_data($file);
$i = 0;
foreach($data['values'] as $dataValues) {
$categories = [];
$brands = [];
$models = [];
foreach($dataValues as $value){
if(array_filter($value)) {
/* If a row does not contain brand/category/model for the product then fetch the resp. info. from previous row */
if(empty(trim($value[0]))) {
$categories[] = $prev_cat;
} else {
$categories[] = strtoupper(trim($value[0]));
$prev_cat = strtoupper(trim($value[0]));
}
if(empty(trim($value[1]))) {
$brands[] = $prev_brand;
} else {
$brands[] = strtoupper(trim($value[1]));
$prev_brand = strtoupper(trim($value[1]));
}
if(empty(trim($value[2]))) {
$models[] = $prev_model;
} else {
$models[] = $value[2];
$prev_model = $value[2];
}
}
}
//insert device category
$this->insert_setups('category', $categories);
//insert brand
$this->insert_setups('brand', $brands);
// Check if branch already exists in the database
$check_branch = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->result();
$branch_arr = [];
//insert branch
if(empty($check_branch)) {
$branch_arr = array(
'name' => $data['branch'][$i].' branch',
'location' => $data['branch'][$i],
'status' => 1,
'created_by' => $this->session->userdata('id'),
'created_on' => date('Y-m-d')
);
$this->global_model->insertData('branch', $branch_arr);
}
$branch_id = $this->global_model->getDetailByWhere('branch', array('name'=>$data['branch'][$i].' branch'))->row()->id;
$db_device_categories = [];
$db_brands = [];
// get categoris, brands
$db_device_categories = $this->arrangeArray('category', $where =array());
$db_brands = $this->arrangeArray('brand', $where =array());
//detail_print($db_brands);
// insert new models from database
foreach(array_unique($models) as $model_key=>$model){
$check_model = $this->global_model->getDetailByWhere('model', array('name'=>$model))->result();
$insert = [];
if(empty($check_model)){
$insert = array(
'name' => $model,
'item_type' => 1,
'category_id' => $db_device_categories[$categories[$model_key]],
'brand_id' => $db_brands[$brands[$model_key]],
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData('model', $insert);
}
}
$db_device_models = [];
// get models from database
$db_device_models = $this->arrangeArray('model', $where = array('item_type'=>1));
$categoriy_id = [];
$brand_id = [];
$model_id = [];
$opening_stock = [];
// arrange the exported array with respective id
foreach($dataValues as $values){
if(array_filter($values)) {
if(empty(trim($values[0]))) {
$category_id = $prev_cat;
} else {
$category_id = strtoupper(trim($values[0]));
$prev_cat = strtoupper(trim($values[0]));
}
if(empty(trim($values[1]))) {
$brand_id = $prev_brand;
} else {
$brand_id = strtoupper(trim($values[1]));
$prev_brand = strtoupper(trim($values[1]));
}
if(empty(trim($values[2]))) {
$model_id = $prev_model;
} else {
$model_id = $values[2];
$prev_model = $values[2];
}
$opening_stock[] = array(
'category_id' => $db_device_categories[$category_id],
'brand_id' => $db_brands[$brand_id],
'model_id' => $db_device_models[$model_id],
'imei' => (string)$values[3],
'cost_price' => isset($values[5]) ? $values[5] : 0,
'selling_price' => isset($values[6]) ? $values[6] : 0
);
}
}
$group_by_model = [];
// group the array by model_id
foreach(array_unique($models) as $model1){
$where = $db_device_models[$model1];
$group_by_model[] = array_filter($opening_stock, function($elements) use ($where){
return $elements["model_id"] == $where;
});
}
if(!$this->purchase_model->insertOpeningStock($group_by_model, $branch_id)){
$this->session->set_flashdata('error', 'Opening stock of devices insertion failed.');
redirect('purchase/uploadExcelFile');
}
$i++;
}
$this->session->set_flashdata('success', 'Opening stock of devices added successfully.');
redirect('purchase/uploadExcelFile');
}
private function arrangeArray($table, $where){
$list = $this->global_model->getDetailByWhere($table, $where)->result_array();
foreach($list as $item){
$name = $item['name'];
$arranged_list[$name] = $item['id'];
}
return !empty($arranged_list) ? $arranged_list : NULL;
}
private function insert_setups($table_name, $setups){
foreach(array_unique($setups) as $value){
$check_setup = $this->global_model->getDetailByWhere($table_name, array('name'=>$value))->result();
if(empty($check_setup)){
$insert = array(
'name' => $value,
'created_by' => $this->session->userdata("id"),
'created_on' => date('Y-m-d'),
);
$this->global_model->insertData($table_name, $insert);
}
}
}
What this function does is, it extracts data from the uploaded excel file and inserts the data to various tables accordingly. Now as you can see, there are multiple queries running in different locations inside the importExcelFile() method. So my question is, how do I use codeigniter transaction in such a way that all the queries inside this function are performed atomically. If any one query fails, all other query's work is rolled back. Also, is this code considered clean ?
P.S. I'm so sorry if my last question was inappropriate here.
this might be helpful to you.
transactions in codeigniter
$this->db->trans_begin();
$this->db->query('AN SQL QUERY...');
$this->db->query('ANOTHER QUERY...');
$this->db->query('AND YET ANOTHER QUERY...');
if ($this->db->trans_status() === FALSE)
{
$this->db->trans_rollback();
}
else
{
$this->db->trans_commit();
}
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.