How to update data if product sku already available in magento using custom script for product import?Product Update with Url_Key & Store_Id Attribute Already Exists error in csv import with magento EECreate categories through installerUpdate custom attribute when product data updated through importCSV import not working - Need AssistanceHow to Import product using CSV?Custom product import script break after 1 product import!Custom csv import using data flow profile not working in magento-1.9.3.1How to update configurable product description using sku via script in magento 2Magento 1.9.2.2 Datwflow Import Product Price Update CSVExport Category name in xml feed Magento 1.9.2

The IT department bottlenecks progress. How should I handle this?

Is there a working SACD iso player for Ubuntu?

Removing files under particular conditions (number of files, file age)

Store Credit Card Information in Password Manager?

What are the purposes of autoencoders?

How to indicate a cut out for a product window

Why did the EU agree to delay the Brexit deadline?

Freedom of speech and where it applies

Where did Heinlein say "Once you get to Earth orbit, you're halfway to anywhere in the Solar System"?

Which one is correct as adjective “protruding” or “protruded”?

Is it possible to have a strip of cold climate in the middle of a planet?

Is this toilet slogan correct usage of the English language?

Is there a name for this algorithm to calculate the concentration of a mixture of two solutions containing the same solute?

Strong empirical falsification of quantum mechanics based on vacuum energy density

Does an advisor owe his/her student anything? Will an advisor keep a PhD student only out of pity?

Count the occurrence of each unique word in the file

If a character has darkvision, can they see through an area of nonmagical darkness filled with lightly obscuring gas?

GraphicsGrid with a Label for each Column and Row

How should I respond when I lied about my education and the company finds out through background check?

Loading commands from file

Fear of getting stuck on one programming language / technology that is not used in my country

Redundant comparison & "if" before assignment

Should I stop contributing to retirement accounts?

Longest common substring in linear time



How to update data if product sku already available in magento using custom script for product import?


Product Update with Url_Key & Store_Id Attribute Already Exists error in csv import with magento EECreate categories through installerUpdate custom attribute when product data updated through importCSV import not working - Need AssistanceHow to Import product using CSV?Custom product import script break after 1 product import!Custom csv import using data flow profile not working in magento-1.9.3.1How to update configurable product description using sku via script in magento 2Magento 1.9.2.2 Datwflow Import Product Price Update CSVExport Category name in xml feed Magento 1.9.2













0















I have created custom import script for simple product csv import in magento. It is working fine for the newly products.
But I want to update the products if sku already exists.
How can I achieve this? I am using the below code :



<?php 
error_reporting(0);

ini_set('max_execution_time', 2000);
ini_set('auto_detect_line_endings', true);
require_once('app/Mage.php'); //Path to Magento

umask(0);

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(0));
$data = glob("customupload/*.csv");
$fileList = array();
foreach ($data as $file)
$fileList[filemtime($file)] = $file;

ksort($fileList);
$myarray = array();
foreach($fileList as $key => $val)
$myarray[] = $val;

$list=array();
if(count($myarray))

/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
$list = explode('/', $myarray[count($myarray)-1]);
array_walk($csv_map, function(&$a) use ($csv_map)
$a = array_combine($csv_map[0], $a);
);

array_shift($csv_map); # remove column header
/*End*/

$message = '';
$count = 1;
foreach($csv_map as $data)
try

$product = Mage::getModel('catalog/product');

$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = $data['attribute set'];
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();

$product->setAttributeSetId($attributeSetId); // need to look this up

$product->setTaxClassId(0); // taxable goods

$product->setVisibility(4); // catalog, search

$product->setStatus(1); // enabled

$product->setWebsiteIDs(1);

$product->setStoreId(1);

$product->setTypeId('simple');

$product->setWarranty('Lifetime');

// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));


// configure stock
$product->setStockData(array(
'use_config_manage_stock' => 1, // use global config ?
'manage_stock' => 0, // shoudl we manage stock or not?
'is_in_stock' => 1
/*'qty' => 2,*/
));
$mediaArray = array(
'thumbnail' => $data['image'],
'small_image' => $data['image'],
'image' => $data['image']
);

// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/product/';

foreach ( $mediaArray as $imageType => $fileName )
$filePath = $importDir . $fileName;
if ( file_exists($filePath) )
try
$product->addImageToMediaGallery($filePath, $imageType, false);
catch (Exception $e)
echo $e->getMessage();

else
echo "Product does not have an image or the path is incorrect. Path was: $filePath<br/>";


//set category

$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $data['Category'])->getFirstItem();

$cat1= $_category->getId();
$expcategory = explode('/',$data['sub category']);
$allsubcatid = array();

foreach($expcategory as $_cat2)


$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $_cat2)->getFirstItem();

$allsubcatid[] = $_category->getId();


//echo '<pre>'; print_r($allsubcatid);die;
$product->setCategoryIds(array($cat1,$allsubcatid));

$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'manufacturer');
$attributeValue = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
foreach($attributeValue as $option)

if (strtolower($option['value']) == strtolower($data['manufacturer']))
$manufacturer = $option['option_id'];


// finally set custom data

foreach($data as $key => $val)
if($key != 'Category')
$capitalword = ucwords(trim($key));
$remove_hyphen = str_replace(' ','',trim($capitalword));
$setdata = $remove_hyphen;
$setdatas = set.$setdata;
$product->$setdatas($val);


$product->setManufacturer($manufacturer);
$product->save();

catch (Exception $e)

Mage::log($e->getMessage(), null, 'configurableProductsDataError.log', true);

$count++;
$c .= $count."<br>";
if($count ==1) break;


echo "Success";


?>
<?php

rename("customupload/".$list[1], "customupload/uploaded/".$list[1]);
?>









share|improve this question
















bumped to the homepage by Community 15 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that

    – user52581
    Apr 22 '17 at 12:09















0















I have created custom import script for simple product csv import in magento. It is working fine for the newly products.
But I want to update the products if sku already exists.
How can I achieve this? I am using the below code :



<?php 
error_reporting(0);

ini_set('max_execution_time', 2000);
ini_set('auto_detect_line_endings', true);
require_once('app/Mage.php'); //Path to Magento

umask(0);

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(0));
$data = glob("customupload/*.csv");
$fileList = array();
foreach ($data as $file)
$fileList[filemtime($file)] = $file;

ksort($fileList);
$myarray = array();
foreach($fileList as $key => $val)
$myarray[] = $val;

$list=array();
if(count($myarray))

/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
$list = explode('/', $myarray[count($myarray)-1]);
array_walk($csv_map, function(&$a) use ($csv_map)
$a = array_combine($csv_map[0], $a);
);

array_shift($csv_map); # remove column header
/*End*/

$message = '';
$count = 1;
foreach($csv_map as $data)
try

$product = Mage::getModel('catalog/product');

$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = $data['attribute set'];
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();

$product->setAttributeSetId($attributeSetId); // need to look this up

$product->setTaxClassId(0); // taxable goods

$product->setVisibility(4); // catalog, search

$product->setStatus(1); // enabled

$product->setWebsiteIDs(1);

$product->setStoreId(1);

$product->setTypeId('simple');

$product->setWarranty('Lifetime');

// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));


// configure stock
$product->setStockData(array(
'use_config_manage_stock' => 1, // use global config ?
'manage_stock' => 0, // shoudl we manage stock or not?
'is_in_stock' => 1
/*'qty' => 2,*/
));
$mediaArray = array(
'thumbnail' => $data['image'],
'small_image' => $data['image'],
'image' => $data['image']
);

// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/product/';

foreach ( $mediaArray as $imageType => $fileName )
$filePath = $importDir . $fileName;
if ( file_exists($filePath) )
try
$product->addImageToMediaGallery($filePath, $imageType, false);
catch (Exception $e)
echo $e->getMessage();

else
echo "Product does not have an image or the path is incorrect. Path was: $filePath<br/>";


//set category

$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $data['Category'])->getFirstItem();

$cat1= $_category->getId();
$expcategory = explode('/',$data['sub category']);
$allsubcatid = array();

foreach($expcategory as $_cat2)


$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $_cat2)->getFirstItem();

$allsubcatid[] = $_category->getId();


//echo '<pre>'; print_r($allsubcatid);die;
$product->setCategoryIds(array($cat1,$allsubcatid));

$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'manufacturer');
$attributeValue = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
foreach($attributeValue as $option)

if (strtolower($option['value']) == strtolower($data['manufacturer']))
$manufacturer = $option['option_id'];


// finally set custom data

foreach($data as $key => $val)
if($key != 'Category')
$capitalword = ucwords(trim($key));
$remove_hyphen = str_replace(' ','',trim($capitalword));
$setdata = $remove_hyphen;
$setdatas = set.$setdata;
$product->$setdatas($val);


$product->setManufacturer($manufacturer);
$product->save();

catch (Exception $e)

Mage::log($e->getMessage(), null, 'configurableProductsDataError.log', true);

$count++;
$c .= $count."<br>";
if($count ==1) break;


echo "Success";


?>
<?php

rename("customupload/".$list[1], "customupload/uploaded/".$list[1]);
?>









share|improve this question
















bumped to the homepage by Community 15 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.















  • Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that

    – user52581
    Apr 22 '17 at 12:09













0












0








0








I have created custom import script for simple product csv import in magento. It is working fine for the newly products.
But I want to update the products if sku already exists.
How can I achieve this? I am using the below code :



<?php 
error_reporting(0);

ini_set('max_execution_time', 2000);
ini_set('auto_detect_line_endings', true);
require_once('app/Mage.php'); //Path to Magento

umask(0);

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(0));
$data = glob("customupload/*.csv");
$fileList = array();
foreach ($data as $file)
$fileList[filemtime($file)] = $file;

ksort($fileList);
$myarray = array();
foreach($fileList as $key => $val)
$myarray[] = $val;

$list=array();
if(count($myarray))

/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
$list = explode('/', $myarray[count($myarray)-1]);
array_walk($csv_map, function(&$a) use ($csv_map)
$a = array_combine($csv_map[0], $a);
);

array_shift($csv_map); # remove column header
/*End*/

$message = '';
$count = 1;
foreach($csv_map as $data)
try

$product = Mage::getModel('catalog/product');

$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = $data['attribute set'];
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();

$product->setAttributeSetId($attributeSetId); // need to look this up

$product->setTaxClassId(0); // taxable goods

$product->setVisibility(4); // catalog, search

$product->setStatus(1); // enabled

$product->setWebsiteIDs(1);

$product->setStoreId(1);

$product->setTypeId('simple');

$product->setWarranty('Lifetime');

// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));


// configure stock
$product->setStockData(array(
'use_config_manage_stock' => 1, // use global config ?
'manage_stock' => 0, // shoudl we manage stock or not?
'is_in_stock' => 1
/*'qty' => 2,*/
));
$mediaArray = array(
'thumbnail' => $data['image'],
'small_image' => $data['image'],
'image' => $data['image']
);

// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/product/';

foreach ( $mediaArray as $imageType => $fileName )
$filePath = $importDir . $fileName;
if ( file_exists($filePath) )
try
$product->addImageToMediaGallery($filePath, $imageType, false);
catch (Exception $e)
echo $e->getMessage();

else
echo "Product does not have an image or the path is incorrect. Path was: $filePath<br/>";


//set category

$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $data['Category'])->getFirstItem();

$cat1= $_category->getId();
$expcategory = explode('/',$data['sub category']);
$allsubcatid = array();

foreach($expcategory as $_cat2)


$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $_cat2)->getFirstItem();

$allsubcatid[] = $_category->getId();


//echo '<pre>'; print_r($allsubcatid);die;
$product->setCategoryIds(array($cat1,$allsubcatid));

$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'manufacturer');
$attributeValue = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
foreach($attributeValue as $option)

if (strtolower($option['value']) == strtolower($data['manufacturer']))
$manufacturer = $option['option_id'];


// finally set custom data

foreach($data as $key => $val)
if($key != 'Category')
$capitalword = ucwords(trim($key));
$remove_hyphen = str_replace(' ','',trim($capitalword));
$setdata = $remove_hyphen;
$setdatas = set.$setdata;
$product->$setdatas($val);


$product->setManufacturer($manufacturer);
$product->save();

catch (Exception $e)

Mage::log($e->getMessage(), null, 'configurableProductsDataError.log', true);

$count++;
$c .= $count."<br>";
if($count ==1) break;


echo "Success";


?>
<?php

rename("customupload/".$list[1], "customupload/uploaded/".$list[1]);
?>









share|improve this question
















I have created custom import script for simple product csv import in magento. It is working fine for the newly products.
But I want to update the products if sku already exists.
How can I achieve this? I am using the below code :



<?php 
error_reporting(0);

ini_set('max_execution_time', 2000);
ini_set('auto_detect_line_endings', true);
require_once('app/Mage.php'); //Path to Magento

umask(0);

Mage::app()->setCurrentStore(Mage::getModel('core/store')->load(0));
$data = glob("customupload/*.csv");
$fileList = array();
foreach ($data as $file)
$fileList[filemtime($file)] = $file;

ksort($fileList);
$myarray = array();
foreach($fileList as $key => $val)
$myarray[] = $val;

$list=array();
if(count($myarray))

/*This will create an array of associative arrays with the first row column headers as the keys.*/
$csv_map = array_map('str_getcsv', file($myarray[count($myarray)-1]));
$list = explode('/', $myarray[count($myarray)-1]);
array_walk($csv_map, function(&$a) use ($csv_map)
$a = array_combine($csv_map[0], $a);
);

array_shift($csv_map); # remove column header
/*End*/

$message = '';
$count = 1;
foreach($csv_map as $data)
try

$product = Mage::getModel('catalog/product');

$entityTypeId = Mage::getModel('eav/entity')
->setType('catalog_product')
->getTypeId();
$attributeSetName = $data['attribute set'];
$attributeSetId = Mage::getModel('eav/entity_attribute_set')
->getCollection()
->setEntityTypeFilter($entityTypeId)
->addFieldToFilter('attribute_set_name', $attributeSetName)
->getFirstItem()
->getAttributeSetId();

$product->setAttributeSetId($attributeSetId); // need to look this up

$product->setTaxClassId(0); // taxable goods

$product->setVisibility(4); // catalog, search

$product->setStatus(1); // enabled

$product->setWebsiteIDs(1);

$product->setStoreId(1);

$product->setTypeId('simple');

$product->setWarranty('Lifetime');

// assign product to the default website
$product->setWebsiteIds(array(Mage::app()->getStore(true)->getWebsite()->getId()));


// configure stock
$product->setStockData(array(
'use_config_manage_stock' => 1, // use global config ?
'manage_stock' => 0, // shoudl we manage stock or not?
'is_in_stock' => 1
/*'qty' => 2,*/
));
$mediaArray = array(
'thumbnail' => $data['image'],
'small_image' => $data['image'],
'image' => $data['image']
);

// Remove unset images, add image to gallery if exists
$importDir = Mage::getBaseDir('media') . DS . 'import/product/';

foreach ( $mediaArray as $imageType => $fileName )
$filePath = $importDir . $fileName;
if ( file_exists($filePath) )
try
$product->addImageToMediaGallery($filePath, $imageType, false);
catch (Exception $e)
echo $e->getMessage();

else
echo "Product does not have an image or the path is incorrect. Path was: $filePath<br/>";


//set category

$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $data['Category'])->getFirstItem();

$cat1= $_category->getId();
$expcategory = explode('/',$data['sub category']);
$allsubcatid = array();

foreach($expcategory as $_cat2)


$_category = Mage::getResourceModel('catalog/category_collection')->addFieldToFilter('name', $_cat2)->getFirstItem();

$allsubcatid[] = $_category->getId();


//echo '<pre>'; print_r($allsubcatid);die;
$product->setCategoryIds(array($cat1,$allsubcatid));

$attribute = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product', 'manufacturer');
$attributeValue = Mage::getResourceModel('eav/entity_attribute_option_collection')
->setAttributeFilter($attribute->getData('attribute_id'))
->setStoreFilter(0, false);
foreach($attributeValue as $option)

if (strtolower($option['value']) == strtolower($data['manufacturer']))
$manufacturer = $option['option_id'];


// finally set custom data

foreach($data as $key => $val)
if($key != 'Category')
$capitalword = ucwords(trim($key));
$remove_hyphen = str_replace(' ','',trim($capitalword));
$setdata = $remove_hyphen;
$setdatas = set.$setdata;
$product->$setdatas($val);


$product->setManufacturer($manufacturer);
$product->save();

catch (Exception $e)

Mage::log($e->getMessage(), null, 'configurableProductsDataError.log', true);

$count++;
$c .= $count."<br>";
if($count ==1) break;


echo "Success";


?>
<?php

rename("customupload/".$list[1], "customupload/uploaded/".$list[1]);
?>






magento-1.9 php import model csv






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 22 '17 at 12:22









Priyank

5,23241952




5,23241952










asked Apr 22 '17 at 11:37









Vinod KumarVinod Kumar

943321




943321





bumped to the homepage by Community 15 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 15 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.














  • Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that

    – user52581
    Apr 22 '17 at 12:09

















  • Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that

    – user52581
    Apr 22 '17 at 12:09
















Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that

– user52581
Apr 22 '17 at 12:09





Where you create product model there ,check product is existing,by checking like $product = Mage::getModel('catalog/product')->loadBySku($sku); and put that $ product in if condition and if product already then no need to create product model direct use $product and set value to it and save that

– user52581
Apr 22 '17 at 12:09










1 Answer
1






active

oldest

votes


















0














Try Using



$_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['sku']);


Or



$product = Mage::getModel('catalog/product');
$product->load($product->getIdBySku($data['sku']));


If the product is found it will load the product and return you the model. If not it will return you an empty model.






share|improve this answer






















    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f171257%2fhow-to-update-data-if-product-sku-already-available-in-magento-using-custom-scri%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Try Using



    $_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['sku']);


    Or



    $product = Mage::getModel('catalog/product');
    $product->load($product->getIdBySku($data['sku']));


    If the product is found it will load the product and return you the model. If not it will return you an empty model.






    share|improve this answer



























      0














      Try Using



      $_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['sku']);


      Or



      $product = Mage::getModel('catalog/product');
      $product->load($product->getIdBySku($data['sku']));


      If the product is found it will load the product and return you the model. If not it will return you an empty model.






      share|improve this answer

























        0












        0








        0







        Try Using



        $_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['sku']);


        Or



        $product = Mage::getModel('catalog/product');
        $product->load($product->getIdBySku($data['sku']));


        If the product is found it will load the product and return you the model. If not it will return you an empty model.






        share|improve this answer













        Try Using



        $_product = Mage::getModel('catalog/product')->loadByAttribute('sku',$data['sku']);


        Or



        $product = Mage::getModel('catalog/product');
        $product->load($product->getIdBySku($data['sku']));


        If the product is found it will load the product and return you the model. If not it will return you an empty model.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Apr 22 '17 at 12:08









        PriyankPriyank

        5,23241952




        5,23241952



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f171257%2fhow-to-update-data-if-product-sku-already-available-in-magento-using-custom-scri%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Magento 2 duplicate PHPSESSID cookie when using session_start() in custom php scriptMagento 2: User cant logged in into to account page, no error showing!Magento duplicate on subdomainGrabbing storeview from cookie (after using language selector)How do I run php custom script on magento2Magento 2: Include PHP script in headerSession lock after using Cm_RedisSessionscript php to update stockMagento set cookie popupMagento 2 session id cookie - where to find it?How to import Configurable product from csv with custom attributes using php scriptMagento 2 run custom PHP script

            Can not update quote_id field of “quote_item” table magento 2Magento 2.1 - We can't remove the item. (Shopping Cart doesnt allow us to remove items before becomes empty)Add value for custom quote item attribute using REST apiREST API endpoint v1/carts/cartId/items always returns error messageCorrect way to save entries to databaseHow to remove all associated quote objects of a customer completelyMagento 2 - Save value from custom input field to quote_itemGet quote_item data using quote id and product id filter in Magento 2How to set additional data to quote_item table from controller in Magento 2?What is the purpose of additional_data column in quote_item table in magento2Set Custom Price to Quote item magento2 from controller

            How to solve knockout JS error in Magento 2 Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Announcing the arrival of Valued Associate #679: Cesar Manara Unicorn Meta Zoo #1: Why another podcast?(Magento2) knockout.js:3012 Uncaught ReferenceError: Unable to process bindingUnable to process binding Knockout.js magento 2Cannot read property `scopeLabel` of undefined on Product Detail PageCan't get Customer Data on frontend in Magento 2Magento2 Order Summary - unable to process bindingKO templates are not loading in Magento 2.1 applicationgetting knockout js error magento 2Product grid not load -— Unable to process binding Knockout.js magento 2Product form not loaded in magento2Uncaught ReferenceError: Unable to process binding “if: function()return (isShowLegend()) ” magento 2