Tuesday, February 24, 2015

update product stock programmatically through command line in Magento

SQL:

SELECT * FROM cataloginventory_stock_status;

SELECT * FROM cataloginventory_stock_item;

Code:

<?php
if (php_sapi_name() !== 'cli' || !empty($_SERVER['REMOTE_ADDR'])) {
  echo 'Must be called from the command line.';
  exit(1);
}

ini_set('max_execution_time', 28800);

require_once '/www/magento1.9.1/app/Mage.php';

#Varien_Profiler::enable();
Mage::setIsDeveloperMode(true);

Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
#Mage::app();

$prodId = 1;
$prodQty = 105;

$updateStockByProductId = updateStockByProductId($prodId, $prodQty);

if ($updateStockByProductId === TRUE) {
  echo 'Yes';
}
else {
  echo 'No';
}

function myUpdateStockByProductId($itemId, $itemQty) {
  $itemId = (int) $itemId;
  $itemQty = (int) $itemQty;

  $stockItem = Mage::getModel('cataloginventory/stock_item')->loadByProduct($itemId);

  if (!$stockItem->getId()) {
    $stockItem->setData('product_id', $itemId);
    $stockItem->setData('stock_id', 1);
  }

  if ($stockItem->getId() > 0) {
    $stockItem->setData('use_config_manage_stock', 1);
    $stockItem->setData('manage_stock', 1);
    $stockItem->setData('qty', $itemQty);
    $stockItem->setData('is_in_stock', ($itemQty > 0 ? 1 : 0));
    $stockItem->save();

    if ($stockItem->getQty() === $itemQty) {
      return TRUE;
    }
  }

  return FALSE;
}
?>

No comments: