I'm trying to write a script to add 10 products to Magento using php/mage.

This is what I have so far, in Magento 1.8.1

ini_set('memory_limit', '-1');
ini_set('display_errors', '1');
require '../app/Mage.php';
$app = Mage::app('default');
$product = Mage::getModel('catalog/product');
$sku = 1;

do {
$product->setName(trim(strip_tags('Unnamed Product')));
$product->setShortDescription(trim(strip_tags('Short Description')));
$product->setPrice(trim(strip_tags('19.99'))); # Set some price
$product->setTaxClassId(2); // taxable goods
$def_attribute_set = Mage::getModel('catalog/product')->getResource()->getEntityType()->getDefaultAttributeSetId();
'use_config_manage_stock' => 1,
'qty' => trim(strip_tags($data[13])),
'min_qty' => 0,
'min_sale_qty' => 0,
'max_sale_qty' => 9999,
'is_qty_decimal' => 0,
'backorders' => 0,
'notify_stock_qty' => 1,
'is_in_stock' => 1
} while ($sku<=10)


I'm trying to tell it to add products, increment the sku by 1, and keep adding and incrementing till it gets to 10. However it only adds one product and then does nothing?

Is there a better way to programatically add products to magento and increment the sku? Also trying to figure out how to get Magento to check for the sku and skip it if it exists and have had zero luck with that as well.


This is happening because for when $sku is 1 and you save the product at the end of the loop, Magento assigns a product id to the product. All subsequent changes will me made the the first product that was created since $product refers to that product object only.

So this will create 1 product and it's sku will be set to 10. Magento identifies if it is an existing object or a new one by determining if $product->getId() has an id in it or if it is set to null. If it is already set then it considers it as an Update operation rather than an insert to create a new one.

To fix this add $product->setData(null); right after the do loop starts:

do {


.. So on...

  • Correct explanation, but $product->setData(null) isn't enough for products, you should use $product->clearInstance() or create a new instance with $product = Mage::getModel('catalog/product'). – Fabian Schmengler Feb 2 '15 at 8:59

PeaceLoveCoding,as you doing auto increment value to product,then you need to get last product sku.

Then you need start auto increment value from


$sku = 1 +(int)$LastProduct->getSku();

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.