0

I'm importing my products in an empty magento store from an .csv and it worked fine while testing with 1 product, but now that I want to import all of them I get the problem the previous product gets overwritten by the next one so after the import I only have one product in my store.

include_once "../app/Mage.php";
include_once "../downloader/Maged/Controller.php";

Mage::init();

// Set the store id
$app = Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
$Simpleproduct = Mage::getModel('catalog/product');

if(($handle = fopen("simple.csv", "r")) !== FALSE){
fgetcsv($handle);
while(($data = fgetcsv($handle, 1000, ';')) !== FALSE){
  try{
    $Simpleproduct
      ->setWebsiteIds(array(1))
      ->setAttributeSetId(4)
      ->setTypeId('simple')
      ->setCreatedAt(strtotime('now'))
      ->setName($data[4])
      ->setWeight(4.0000)
      ->setStatus(1) //(1 - enabled, 2 - disabled)
      ->setTaxClassId(2) //(0 - none, 1 - default, 2 - taxable, 4 - shipping)
      ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_NOT_VISIBLE)
      ->setPrice($data[3]);

     if($Simpleproduct->save()){
        echo "product ".$sku." Was created<br>";
        $row++;
     }
  }catch(Exception $e){
    die();
    echo "<p><b>";
    echo $e;
    echo "</p></b><br>";
    echo $data[4];
  }
  }
}else{
    echo "Handle == false";
 }
1

This is your problem.

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

is outside the while loop so you use the same product instance everytime.
The first product gets inserger. When calling save() the product instances gets an id and any other operation you do with the product instance will affect the product with that id.
Move the line above inside the while loop and it should work.

while(($data = fgetcsv($handle, 1000, ';')) !== FALSE){
  try{
     $Simpleproduct = Mage::getModel('catalog/product');
      ....
  } catch .... {
  }
}
0

You can keep $Simpleproduct outside loop, just add this line in the end of try block

$Simpleproduct->unsetData();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.