3

I want to update just the prices of all products in my Magento 2 store and to do this quickly and easily i have a CSV with sku and price and was hoping price could be updated using sku as an identifier.

Using the default magento import process however i am being asked for extra fields including product_type,attribute_set_code,name ect.

Is there a quick and easy way to do this with just sku and price as none of these other fields need modifying?

3 Answers 3

2

Here is the simple script that does the job for you (easiest & fastest approach):

<?php
/**
 *
 * @author Raj KB<[email protected]>
 * @website http://www.magepsycho.com
 * @extension MassImporterPro: Pricing - http://www.magepsycho.com/mass-importer-pro-price-importer-regular-special-tier-group.html
 */
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Capture warning / notice as exception
set_error_handler('ctv_exceptions_error_handler');
function ctv_exceptions_error_handler($severity, $message, $filename, $lineno) {
    if (error_reporting() == 0) {
        return;
    }
    if (error_reporting() & $severity) {
        throw new ErrorException($message, 0, $severity, $filename, $lineno);
    }
}

require __DIR__ . '/../app/bootstrap.php';
$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);

$obj = $bootstrap->getObjectManager();

$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('adminhtml');


/**************************************************************************************************/
// UTILITY FUNCTIONS - START
/**************************************************************************************************/
function _mpLog($data, $includeSep = false)
{
    $fileName = BP . '/var/log/m2-magepsycho-import-prices.log';
    if ($includeSep) {
        $separator = str_repeat('=', 70);
        file_put_contents($fileName, $separator . '<br />' . PHP_EOL,  FILE_APPEND | LOCK_EX);
    }
    file_put_contents($fileName, $data . '<br />' .PHP_EOL,  FILE_APPEND | LOCK_EX);
}

function mpLogAndPrint($message, $separator = false)
{
    _mpLog($message, $separator);
    if (is_array($message) || is_object($message)) {
        print_r($message);
    } else {
        echo $message . '<br />' . PHP_EOL;
    }

    if ($separator) {
        echo str_repeat('=', 70) . '<br />' . PHP_EOL;
    }
}

function getIndex($field)
{
    global $headers;
    $index = array_search($field, $headers);
    if ( !strlen($index)) {
        $index = -1;
    }
    return $index;
}

function readCsvRows($csvFile)
{
    $rows = [];
    $fileHandle = fopen($csvFile, 'r');
    while(($row = fgetcsv($fileHandle, 0, ',', '"', '"')) !== false) {
        $rows[] = $row;
    }
    fclose($fileHandle);
    return $rows;
}

function _getResourceConnection()
{
    global $obj;
    return $obj->get('Magento\Framework\App\ResourceConnection');
}

function _getReadConnection()
{
    return _getConnection('core_read');
}

function _getWriteConnection()
{
    return _getConnection('core_write');
}

function _getConnection($type = 'core_read')
{
    return _getResourceConnection()->getConnection($type);
}

function _getTableName($tableName)
{
    return _getResourceConnection()->getTableName($tableName);
}

function _getAttributeId($attributeCode)
{
    $connection = _getReadConnection();
    $sql = "SELECT attribute_id FROM " . _getTableName('eav_attribute') . " WHERE entity_type_id = ? AND attribute_code = ?";
    return $connection->fetchOne(
        $sql,
        [
            _getEntityTypeId('catalog_product'),
            $attributeCode
        ]
    );
}

function _getEntityTypeId($entityTypeCode)
{
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
    return $connection->fetchOne(
        $sql,
        [
            $entityTypeCode
        ]
    );
}

function _getIdFromSku($sku)
{
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne(
        $sql,
        [
            $sku
        ]
    );

}

function checkIfSkuExists($sku)
{
    $connection = _getConnection('core_read');
    $sql        = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne($sql, [$sku]);
}

function updatePrices($sku, $price, $storeId = 0)
{
    $connection     = _getWriteConnection();
    $entityId       = _getIdFromSku($sku);
    $attributeId    = _getAttributeId('price');

    $sql = "INSERT INTO " . _getTableName('catalog_product_entity_decimal') . " (attribute_id, store_id, entity_id, value) VALUES (?, ?, ?, ?) ON DUPLICATE KEY UPDATE value=VALUES(value)";
    $connection->query(
        $sql,
        [
            $attributeId,
            $storeId,
            $entityId,
            $price
        ]
    );
}

/**************************************************************************************************/
// UTILITY FUNCTIONS - END
/**************************************************************************************************/

try {
    $csvFile        = 'var/import/prices.csv'; #EDIT - The path to import CSV file (Relative to Magento2 Root)
    $csvData        = readCsvRows(BP . '/' . $csvFile);
    $headers        = array_shift($csvData);

    $count   = 0;
    foreach($csvData as $_data) {
        $count++;
        $sku   = $_data[getIndex('sku')];
        $price = $_data[getIndex('price')];

        if ( ! checkIfSkuExists($sku)) {
            $message =  $count .'. FAILURE:: Product with SKU (' . $sku . ') doesn\'t exist.';
            mpLogAndPrint($message);
            continue;
        }

        try {
            updatePrices($sku, $price);
            $message = $count . '. SUCCESS:: Updated SKU (' . $sku . ') with price (' . $price . ')';
            mpLogAndPrint($message);
        } catch(Exception $e) {
            $message =  $count . '. ERROR:: While updating  SKU (' . $sku . ') with Price (' . $price . ') => ' . $e->getMessage();
            mpLogAndPrint($message);
        }
    }
} catch (Exception $e) {
    mpLogAndPrint(
        'EXCEPTION::' . $e->getTraceAsString()
    );
}

For details please refer the article - http://www.blog.magepsycho.com/magento2-fastest-way-import-update-product-prices-bulk/

UPDATE
New module for importing all prices(regular, special, tier & customer group price) in Magento 2 has been released, please check it out:
https://www.magepsycho.com/magento2-mass-regular-special-tier-group-price-importer.html

2
  • This script prompts the following error (on localhost): "EXCEPTION::#0 C:\Server\htdocs\pub\update-prices.php(182): ctv_exceptions_error_handler(8, 'Undefined offse...', 'C:\\Server\\htdoc...', 182, Array) #1 {main}" Apr 11, 2019 at 15:49
  • Or you can use the ready-made extension with GUI - magepsycho.com/…
    – MagePsycho
    May 13, 2019 at 13:15
1

The fastest method in my mind is:

  1. Export your products into CSV first, then just edit the column price to update the product price.

  2. Import the edited CSV into Magento, remember to choose Add/Update on Import Behaviour.

REF: https://www.alexcorradi.org/blog/a-guide-on-how-to-import-export-products-in-magento-2

0

You can also simple write two column in csv that is sku and price and import them,that will update vary fast.

1
  • I can't seem to do this i am asked for additional fields, how do you get it to work with just these 2 fields?
    – harri
    Jun 23, 2017 at 14:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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