No results found

Try a different search query

Popular searches:

Add to Cart

Cart

You have no purchases yet

Browse Marketplace
Original Subtotal:
Product discounts:
Quantity Discount:
Total:
View Cart
API and integrations

OpenCart Product Import Script: Fast and Duplicate-Free for 3.0 and 4.1

How to write a product import script for OpenCart 3.0 and 4.1: a deduplication key, mapping table, batch requests, SEO URLs, images and re-runs without duplicates.

12 min read OC 3.0 OC 4.1

An OpenCartA free open-source CMS for online stores, written in PHP with a MySQL/MariaDB database. Everything that is not part of the core is added through extensions. More in the glossary → productA catalog item with a name, price, description, and photos. More in the glossary → import runs fast and without duplicates when it relies on its own mapping table of "external id → product_id" and batch queries, rather than searching by name or SKU for every row. The core has no unique external key for products in either 3.0 or 4.1, so this is where duplicates most often appear. Below we cover which tables you need to fill so the product appears on the storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →, how to update tens of thousands of items in minutes, and what changed in the 4.1 schema.

Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

Why do duplicates appear, and which key should you search by?

A typical "first" script looks up each price list row by SELECT product_id FROM product WHERE sku = ... and, if nothing is found, inserts a new product. This creates duplicates and slows things down for several reasons.

  • The SKU is not unique. In 3.0, the product.sku column has neither a unique index nor a regular one. A manager could create two products with the same SKU, and some products have an empty one.
  • In 4.1, the product table no longer has SKUs. SKU, UPC, EAN, JAN, ISBN, and MPN were moved to a separate product_code table with the columns product_id, code, and value. The type reference is in the identifier table with codes such as SKU, UPC, and so on. There is an index on code and product_id, but none on value, so searching by code value scans all rows of that type.
  • Suppliers change SKUs and names. A key that seems stable often turns out not to be after six months.
  • One query per row. 20,000 price list rows mean 20,000 search queries and as many updates, each with network latency to MySQL.

A more reliable approach is a mapping table with a unique key on the pair "source + external id". The external id is an identifier the supplier guarantees will not change (a code in their database, an id in the XML feed). The core table schemas are described in the article about the product table and related tables.

Example: import mapping table

CREATE TABLE IF NOT EXISTS `oc_myimport_map` (
  `source` varchar(32) NOT NULL,
  `external_id` varchar(64) NOT NULL,
  `product_id` int(11) NOT NULL,
  `hash` char(32) NOT NULL DEFAULT '',
  `date_seen` datetime NOT NULL,
  PRIMARY KEY (`source`, `external_id`),
  KEY `product_id` (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

The hash column stores an md5 hash of the meaningful row fields (price, quantity, name). If the hash has not changed, the row can be skipped entirely. On a daily price update, usually only a small share of items changes, so this gives the biggest speed gain. date_seen is needed to find products that have disappeared from the feed. General rules for module tables, including why InnoDB is used even in 3.0, are covered in the article about custom module tables.

Which tables must be filled so the product appears on the storefront?

A new product is not a single row. If you skip even one table from this list, the product will exist in the admin but not on the site, or it will lack a name in a given language.

TableWhat it containsConsequence if skipped
productmodel, price, quantity, status, availability date, imagethe product does not exist
product_descriptionname, description, meta tags for each languagethe product disappears from the storefront in that language
product_to_storestore assignment (store_id 0 for the default store)the product is not shown in any store
product_to_categorycategoriesthe product is not visible in the catalog, only via a direct link and in search
seo_urlSEO URL for each store and languagean address like index.php?route=product/product&product_id=...
product_code (4.1 only)SKU, EAN, and other codesthe SKU is not visible in the admin or feeds

The storefront shows a product only when three conditions are met at once: status = 1, date_available is no later than today's date, and there is a row in product_to_store for the current store. In 3.0, date_available defaults to 0000-00-00, so if you don't set it explicitly, the condition is met. However, in MySQL strict mode such a date may fail to insert, so it is better to write CURDATE() explicitly.

Required columns without a default value

In 3.0, the columns model, sku, upc, ean, jan, isbn, mpn, location, stock_status_id, manufacturer_id, tax_class_id, date_added, and date_modified in the product table are declared as NOT NULL without DEFAULT. On a server with STRICT_TRANS_TABLES, an insert without them fails with the error "Field ... doesn't have a default value". Pass them explicitly, at least as an empty string or zero. description, tag, meta_title, meta_description, and meta_keyword in product_description behave the same way in both versions.

SEO URL

  • OpenCart 3.0: seo_url has the columns store_id, language_id, query, and keyword. For a product, query = 'product_id=123'.
  • OpenCart 4.1: instead of query there are two columns, key and value (key = 'product_id', value = '123'), plus sort_order.

In 3.0, the keyword must be unique within a store across all languages: the storefront looks it up only by keyword and store_id, without language_id, and the product form in the admin also checks for matches within the store. So the same word for two languages of one store causes a conflict. In 4.1, it is safest to follow the same rule. The core has no unique index for this. Before inserting, check whether such a keyword is already taken, and add a suffix (for example, the product id). How the core parses these addresses is explained in the article about the seo_url table.

How to write the script: CLI, not an admin page

An import of thousands of items should not depend on the web server or browser timeout. Run it from the command line or a system cron. The simplest approach is a separate PHP script that reads the constants from the store's config.php (DB_HOSTNAME, DB_USERNAME, DB_PASSWORD, DB_DATABASE, DB_PORT, DB_PREFIX, DIR_IMAGE) and works with the database through PDO. The installer writes these constants in both versions. This way the script works with 3.0 and 4.1 and does not pull in the registryA shared container of objects ($this->config, $this->db). More in the glossary →, session, or events.

Pay attention to encoding. The skeleton below connects with charset=utf8mb4, and core tables differ across releases. In 3.0.4.1 they are in utf8 (utf8_general_ci), so 4-byte characters (emoji) from the feed will cause an "Incorrect string value" error in strict mode. Filter out such characters or connect with charset=utf8. In 3.0.5.1 and 4.1, the core tables are in utf8mb4, but core 3.0.5.1 works through the utf8 connection, so the admin and storefront of 3.0 will not read saved emoji correctly. For 3.0, it is better to filter them out in both releases.

Example: CLI import skeleton (3.0 and 4.1)

<?php
// php import.php /path/to/price.csv
if (PHP_SAPI !== 'cli') {
    exit('CLI only');
}

require __DIR__ . '/../config.php';

$lock = fopen(sys_get_temp_dir() . '/myimport.lock', 'c');

if (!flock($lock, LOCK_EX | LOCK_NB)) {
    exit("Already running\n");
}

$pdo = new PDO('mysql:host=' . DB_HOSTNAME . ';port=' . DB_PORT . ';dbname=' . DB_DATABASE . ';charset=utf8mb4', DB_USERNAME, DB_PASSWORD, [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
]);

$p = DB_PREFIX;

// 1. Уся таблиця відповідностей у пам'ять одним запитом
$map = [];

foreach ($pdo->query("SELECT external_id, product_id, hash FROM {$p}myimport_map WHERE source = 'supplier1'") as $row) {
    $map[$row['external_id']] = $row;
}

// 2. Потокове читання файлу, без завантаження цілком
$file = fopen($argv[1], 'r');
$header = fgetcsv($file, 0, ';');

$batch = [];

while (($line = fgetcsv($file, 0, ';')) !== false) {
    $row = array_combine($header, $line);
    $hash = md5($row['price'] . '|' . $row['qty'] . '|' . $row['name']);

    if (isset($map[$row['id']]) && $map[$row['id']]['hash'] === $hash) {
        continue; // нічого не змінилось
    }

    $batch[] = $row + ['hash' => $hash];

    if (count($batch) >= 500) {
        processBatch($pdo, $batch, $map);
        $batch = [];
    }
}

if ($batch) {
    processBatch($pdo, $batch, $map);
}

Locking via flock() prevents two cron runs from working at the same time. Without it, a slow import that has not finished before the next run creates the same products twice. fgetcsv() reads the file line by line, so a price list of hundreds of megabytes does not hit the memory_limit limit. For XML, XMLReader works the same way instead of simplexml_load_file().

An alternative is to run the import as a module: in 4.1, a built-in cron task; in 3.0, a controllerCode that receives a request and prepares data. More in the glossary → called by the system cron. This gives access to core models and module settings, but you must monitor execution time. Both approaches are covered in the article about cron in OpenCart.

How to update thousands of products quickly?

Handle new and existing products differently. New products are usually few, and they can be inserted one by one with all related tables. Existing products may number tens of thousands and must be updated in batches.

Batch update of price and quantity

Instead of 500 separate UPDATE statements, load the batch into a temporary table with one multi-row INSERT and update product with a single UPDATE ... JOIN:

Example: batch update through a temporary table

CREATE TEMPORARY TABLE tmp_import (
  product_id int(11) NOT NULL PRIMARY KEY,
  price decimal(15,4) NOT NULL,
  quantity int(11) NOT NULL
);

INSERT INTO tmp_import (product_id, price, quantity) VALUES
  (101, 1250.0000, 4),
  (102, 980.0000, 0),
  (103, 3100.0000, 12);

UPDATE oc_product p
JOIN tmp_import t ON t.product_id = p.product_id
SET p.price = t.price, p.quantity = t.quantity, p.date_modified = NOW();

TRUNCATE tmp_import;

Build the values in VALUES with type casting ((int), (float)), and escape strings with $pdo->quote() or prepared statements. Data from a supplier is the same kind of external input as a form on the site. The principles are described in the article about safe SQL queries.

Transactions: 4.1 yes, 3.0 no

  • OpenCart 4.1: core tables use InnoDB. Wrap each batch in beginTransaction() and commit(). This is both faster (one log write per batch) and safer: a failure in the middle of a batch will not leave a product without a description.
  • OpenCart 3.0: almost all core tables use MyISAM, and there are no transactions. The BEGIN and COMMIT commands run without errors but roll back nothing. So the order of operations must allow a repeated run to finish unfinished work: first product, then descriptions and assignments, and only at the very end the row in the mapping table.

Because the mapping table is filled last, an import interrupted in 3.0 will not find the product in the map on the next run and will create it again. To prevent this, write the row with product_id into the map right after the insert into product, and find "incomplete" products (without a description or store) with a separate query and finish them.

Should you use addProduct() from the admin?

The admin model catalog/product has addProduct() and editProduct(), which fill all tables correctly. But they are designed for a single form. editProduct() deletes and re-inserts all related rows (descriptions, categories, attributes, images). Both methods clear the product cache at the end. On tens of thousands of products this is many times slower than batch SQL, and it also requires loading the admin environment. For new products in a small import, this is acceptable. For daily updates of prices and quantities, it is not.

Images, missing products, and cache

Images

The product.image column and the product_image table store the path relative to the image directory, for example catalog/import/12345.jpg. Put the file in DIR_IMAGE . 'catalog/import/'. The core creates thumbnails of the needed sizes on first display. Don't download images every time: check whether the file already exists, and update it only when the address in the feed has changed. Downloading images is the slowest part of an import, so it is worth moving into a separate pass with a time limit.

Products missing from the feed

Do not delete them. product_id is referenced by orders, reviews, SEO URLs, and, if the product comes back in the feed, your mapping table. Find records in the map with date_seen older than the current run and set the products to quantity = 0 or status = 0, depending on whether the store wants to show "out of stock."

Cache

Direct SQL bypasses models, so the core cache is not cleared. The file cache is in the DIR_CACHE directory with names like cache.product.*. After an import, delete files with the prefix cache.product. (or the entire cache if the import changed categories or manufacturers). If the store uses Redis or Memcached, clear the cache using the corresponding driver's tools.

Список товарів: перевірте ціну, кількість і статус імпортованих позицій
Product list: check the price, quantity, and status of the imported items · OpenCart 4.1.0.4

If writing an import yourself doesn't make sense, look at the ready-made product import and export for XLSX and CSV or the overview of price list import.

Summary

  • A mapping table with a unique "source + external id" key removes duplicates, not a SKU search. In 4.1, SKUs have also moved to product_code.
  • A product on the storefront needs product, product_description for each language, product_to_store, categories, and seo_url (query in 3.0, key/value in 4.1).
  • Pass all NOT NULL columns that have no default value, otherwise MySQL strict mode will stop the insert.
  • Run from the CLI with locking, read the file as a stream, and skip unchanged rows by hash.
  • Update in batches through a temporary table. In 4.1, wrap each batch in a transaction; in 3.0, order the operations so that a repeated run finishes what was interrupted.
  • Disable products that have disappeared rather than deleting them. After the import, clear the product cache.

Other materials on data exchange with external systems, including order webhooks and a custom JSON endpoint, are collected in the "API and Integrations" section.

FAQ

Can I add a unique index on sku in the product table?
In 3.0 it is technically possible, but first you have to remove all duplicates and empty values, and a core update or another module may break because of it. A separate mapping table gives the same result without changing the core schema.
How do I import product attributes and options?
Attributes are written to product_attribute with the attribute id and text for each language; options go to product_option and product_option_value. Keep attribute and option dictionaries in the mapping table too, so identical names are not duplicated.
How long should importing 20,000 products take?
It depends on the server, the number of images and the share of changed items. A batch update of prices and stock without images usually takes minutes, while most of the time goes to downloading images.
Will module events fire when importing with direct SQL?
No, OpenCart events are tied to model and controller calls. If a module, such as a feed or search, needs to know about changes, update its data separately or call its model after the import.
Was this article helpful?
Thanks for your feedback!

Related articles

Didn't find the answer?

Ask the community: OpenCart developers answer on the forum.

Ask on the forum
We use cookies

We use cookies and similar technologies to improve your experience, analyse traffic, and show personalised ads. Read our Cookie Policy for details.