How to fast stock update Magento

If you ever tried to import product stocks in Magento I’m sure you noticed is extremly slow.

Doesn’t matter how many fields you set in the CSV file it always takes the same time.

Digging arround I found this amazing code.

Create a CSV File

/var/import/updateStockLevels.csv

Place your CSV file like I wrote above.

You can add many fields but I would suggest 2 or 3 (to be faster)

qty
min_qty
use_config_min_qty
is_qty_decimal
backorders
use_config_backorders
min_sale_qty
use_config_min_sale_qty
max_sale_qty
use_config_max_sale_qty
is_in_stock
use_config_notify_stock_qty
manage_stock
use_config_manage_stock
stock_status_changed_automatically
type_id

I will use the SKU and the QTY. My CSV file content looks like:

"sku","qty"
"123456789","10"

Code

Create a PHP file in your root folder with this content.

<?
 define('MAGENTO', realpath(dirname(__FILE__)));
 require_once MAGENTO . '/app/Mage.php';
 
 umask(0);
 Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
 $count = 0;
 
 $file = fopen(MAGENTO . '/var/import/updateStockLevels.csv', 'r');
 while (($line = fgetcsv($file)) !== FALSE) {
 
 if ($count == 0) {
 foreach ($line as $key=>$value) {
 $cols[$value] = $key;
 }
 }
 
 $count++;
 
 if ($count == 1) continue;
 
 #Convert the lines to cols
if ($count > 0) {
 foreach($cols as $col=>$value) {
 unset(${$col});
 ${$col} = $line[$value];
 }
 }
 
 // Check if SKU exists
 $product = Mage::getModel('catalog/product')->loadByAttribute('sku',$sku);
 
 if ( $product ) {
 
 $productId = $product->getIdBySku($sku);
 $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($productId);
 $stockItemId = $stockItem->getId();
 $stock = array();
 
 if (!$stockItemId) {
 $stockItem->setData('product_id', $product->getId());
 $stockItem->setData('stock_id', 1);
 } else {
 $stock = $stockItem->getData();
 }
 
 foreach($cols as $col=>$value) {
 $stock[$col] = $line[$value];
 }
 
 foreach($stock as $field => $value) {
 $stockItem->setData($field, $value?$value:0);
 }
 
 
 $stockItem->save();
 
 unset($stockItem);
 unset($product);
 }
 
 echo "<br />Stock updated $sku";
 
 }
 fclose($file);
 
?>

Run it and have fun!

You’re done. Please try it your self and fly like a thunder ;)

Product Import

No there is no fast product import, yet.

Tags:

27 Responses to “How to fast stock update Magento”

  1. André September 1, 2011 at 5:09 am #

    Hi, i`m using this to update my status and it`s working very well. We have more than 5000 products on database. Sometimes the php function does not ends and timeout. What can i do? Maybe updating half of the stock in each function? Hope you can help me, thank you.

    • Rick September 1, 2011 at 9:02 am #

      Yes, perhaps you could try to do it in two times.

      Upload 2 CSV files with 2500 each.

      If that’s a lot of trouble you may ask for a server upgrade, having more RAM and CPU it might help your store ;)

      Regards

  2. pentlja January 26, 2012 at 10:22 am #

    Hey dude.. you rock, but tell me one thing The stock id will automatically will get set? specially visibilty and Is in stock attribute?

    • Rick January 26, 2012 at 10:33 am #

      hmmmm I think it will only update the defined fields in the CSV.

      Regards

  3. pentlja January 26, 2012 at 10:39 am #

    Hi again, after rechecking your script, No wonder Your php script completely rock but whenever I update stuff my stock availabilty remains out of stock and same with visibilty, Can you tell me how to add these two attributes also?

    Regards,

    • Rick January 26, 2012 at 10:53 am #

      well in the example you already have is_in_stock and qty fields

      Regards

  4. Ashish January 26, 2012 at 12:17 pm #

    Thankx, Its perfect solution :)
    Do you have any idea where can i exceed execution time? I have tried my php.ini and increase execution time but doesnt work, so any other idea?
    It shows me this error: Maximum execution time of 30 seconds exceeded in /home/pentljac/domains/pentlja.com/public_html/app/code/core/Mage/Eav/Model/Config.php on line 560

    • Rick January 26, 2012 at 12:19 pm #

      Try to contact your Hosting provider. Perhaps they have limited that resource from their side.

      Regards

  5. Ashish March 6, 2012 at 3:35 pm #

    Hey, I am looking for some script like this which will add new products in my store but without replacing any information about current products.

    Can you do that?
    It will b great for me.

    • Rick March 6, 2012 at 3:43 pm #

      I’m sorry but I can’t.

      Best of luck !

      Ps: I’ve removed your e-mail to prevent spam.

  6. JBH May 16, 2012 at 5:51 am #

    Awesome code – I’ve been looking for something like this for weeks. Thanks!

    By the way, in Magento 1.7 (and maybe other versions, I don’t know) there is no /var/import/ folder, instead they combined the import and export folders into /var/importexport/

    • JBH May 16, 2012 at 5:53 am #

      …which requires a change of the folder location on ~ line 9 of the php file above.

    • Rick May 16, 2012 at 8:12 am #

      Thanks for the heads up JBH ;)

  7. Kevin June 26, 2012 at 12:45 am #

    Thanks for the script. It works beautifully with test CSV file.
    However, my POS creates CSV file but it puts different heading so script does not work. I want to automate the process so is there any way to change the names of headers?

    Script requires the headers to be
    “sku”,”qty”

    my CSV is
    “ITEM”,”STOCK”

    Is there any way for these to different names to be linked within the script so that script sees ITEM as sku and STOCK as qty?

    Thanks for your help.

    Kevin

    • Rick June 26, 2012 at 9:09 am #

      Hey Kevin,

      Have you actually tried to run the script with your custom fields?

      The script looks at the first line (headers) and uses that key. That why you can set any field in there.

      Let me know,

      Cheers.

  8. Thomas September 17, 2012 at 3:54 pm #

    Hello Rick

    Awesome script thanks! I have same problem that csv is using these headers “ITEM”,”STOCK”

    I tried to run the script with “ITEM”,”STOCK” in csv but nothing is updated.

    Any suggestions?

    • Rick September 24, 2012 at 7:43 pm #

      That’s weird. I’m guessing you’re using Magento 1.7, right?

      Have you tried using other fields?

      Do you have the magento cache on?

      Did you rewrite the index catalog?

      Cheers

  9. Jerick September 24, 2012 at 6:32 pm #

    Hey Rick, You made a simple, but great solution for our problem. Magento 1.7 import has a BUG : error in qty, and your script saved me for $2000.

    Great!

    • Rick September 24, 2012 at 7:42 pm #

      Hi Jerick,

      I’m glad it helped !

      Feel free to suscribe to my RSS Feed to get future posts :)

      Cheers

  10. Max July 19, 2013 at 2:45 pm #

    Thanks, it s working Great !!

    • Rick July 19, 2013 at 8:38 pm #

      Have you tried with the latest stable version? Did you have to change anything?

      Cheers.

  11. daniel November 28, 2013 at 3:34 am #

    Hi Rick,

    You are a superstar!!! I love this script thanks a million it is saving me loads of time! I was wondering if there is anyway to alter the script so that teh headers are pre-defined and do not rely on the first row. The reason I ask is that my supplier provides me with a csv that has the ‘sku” in the first column and the “qty” in the second, with no row labels at the top?

    Obviously your are busy, and only if it is a easy change I know you are doing this for free so no need to worry if you have not got the time.

    Thanks,

    Danny

    • Rick November 28, 2013 at 8:18 am #

      Hi Danny,

      I guess you could hardcode the values without the first row.

      However you should try to ask your supplier, maybe he can change his output so you get the perfect CSV.

      Cheers

  12. Matt June 26, 2014 at 11:05 pm #

    FYI instead of unset() you could call $obj->clearInstance(); – better way to free memory in a loop when you’re using Magento models.

    • Rick June 27, 2014 at 9:20 am #

      Thanks for the tip Matt!

  13. James June 30, 2014 at 6:35 pm #

    Hi Rick!

    This is really great job!
    Can you just add one more thing so that I can add qty from current qty such as, “123456”, “+10″ or “123456”,”-5″
    Thank you again.

    • Rick June 30, 2014 at 9:08 pm #

      Wrote this post 4 years ago, does this still work on Magento 1.9.1? :)

      I would guess you need to play around this line:

      $stockItem->setData($field, $value?$value:0);

      Don’t have the time to do testing though.

      If you happen to find the solution, please let us know!

Leave a Reply

Add <code> Some Code </code> by using this tags.