# Custom Tables for OpenCart Modules: Structure, Database Work and Migrations Between Versions

> When an OpenCart module needs its own tables, how to design and maintain them, how to clean up data left behind by the core, and how to update the schema between module versions.

Джерело: https://opencartcode.com/en/wiki/dev-extensions/opencart-module-tables
OpenCart: 3.0, 4.1
Оновлено: 2026-11-25

[OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart) [module](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#module) tables are needed when the data goes beyond a few settings: logs, bindings to products or orders, queues, API response caches. You create them in `install()` with the prefix `DB_PREFIX`, and you work with them through `$this->db` in the module's model. The hard part starts with the second version of the module, when the schema has to change in stores that already have it installed. Below is how to design tables so they don't conflict with the core, and how to write migrations that don't break customers' stores.

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

## When is a custom table needed, and when is it not?

Switches, texts, API keys and other small arrays are better kept in `setting`, and you don't need a separate table for them. The core loads the entire `setting` table on every request, so anything that grows with the store becomes dead weight on every page. For more on this, see the article [module settings and the setting table](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-setting).

A custom table is needed if at least one of these conditions holds:

- records grow along with the catalog, orders or time (sync log, shipping label status history);
- data must be searched, filtered or sorted by a field;
- data changes while the [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) is running, for example counters, queues or cache;
- other entities are linked to the record: [product](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#product), order, customer, store, language.

The opposite extreme also happens: adding a column to a core table, for example `product`, via `ALTER TABLE`. It's tempting, because the column immediately appears in `SELECT *` queries. But OpenCart updates, migrations between versions and other developers' modules don't know about your column. A separate table with `product_id` is safer and is removed together with the module.

## How do you name and design a table?

The name consists of `DB_PREFIX` and the module code: `DB_PREFIX . 'mymodule_log'`. The store prefix can be anything, not only `oc_`, so a hard-coded table name would break the module for some customers. The module code in the name protects against clashes with core tables and tables from other authors' modules.

Example

```sql
CREATE TABLE IF NOT EXISTS `oc_mymodule_product` (
  `product_id` INT(11) NOT NULL,
  `store_id` INT(11) NOT NULL DEFAULT '0',
  `external_id` VARCHAR(64) NOT NULL DEFAULT '',
  `price` DECIMAL(15,4) NOT NULL DEFAULT '0.0000',
  `date_modified` DATETIME NOT NULL,
  PRIMARY KEY (`product_id`, `store_id`),
  KEY `external_id` (`external_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
```

Several decisions in this example are deliberate:

- **Types as in the core.** Identifiers have the type `INT(11)`, money has `DECIMAL(15,4)`, like the `price` column in `product`. This way `JOIN` and comparisons work without casts.
- **Composite key for languages and stores.** The core does the same: `product_description` has the primary key `(product_id, language_id)`. For the module's language texts use `(id, language_id)`, for per-store settings use `(id, store_id)`.
- **Encoding.** Create module tables with `DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci` or don't specify `COLLATE` at all, so the table takes the database collation. The `utf8mb4_general_ci` comparison is not used by the core: in 3.0.4.1 core tables use `utf8` / `utf8_general_ci`, and in 3.0.5.1 and 4.1 they use `utf8mb4` / `utf8mb4_unicode_ci`. If the store was moved or changed manually, check its table collation via `SHOW TABLE STATUS` and use the same one. Mismatched collations cause the "Illegal mix of collations" error in `JOIN` on text fields that involve core tables.
- **Engine.** **OpenCart 3.0:** almost all core tables are created as MyISAM. **OpenCart 4.1:** the core schema uses InnoDB. For module tables InnoDB works in both versions: it provides transactions and row locking for data written by the storefront.
- **Default values.** Set `DEFAULT` for all columns except keys. The core in both versions disables MySQL strict mode for its connection, so a missing field won't raise an error, but without `DEFAULT` a non-obvious empty value will end up there. Besides, a migration can add a new column with `DEFAULT` to existing rows without problems.

## How do you work with the table in the model?

The module's model receives the database object as `$this->db`. The methods `query`, `escape`, `getLastId` and `countAffected` exist in both branches; in 4.1 they are typed. The connection check differs: `connected()` in 3.0 and `isConnected()` in 4.1. Main methods:

| Method | What it returns |
| --- | --- |
| `query($sql)` | For SELECT, an object with `row` (the first row), `rows` (all rows) and `num_rows`; for other queries `true`. On error it throws an exception with the SQL text |
| `escape($value)` | An escaped string for insertion inside quotes |
| `getLastId()` | The ID of the last `INSERT` |
| `countAffected()` | The number of changed rows |

Example

```php
// OpenCart 4.1: extension/mymodule/admin/model/module/mymodule.php
public function getProduct(int $product_id, int $store_id = 0): array {
	$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "mymodule_product` WHERE `product_id` = '" . (int)$product_id . "' AND `store_id` = '" . (int)$store_id . "'");

	return $query->row;
}

public function editProduct(int $product_id, int $store_id, string $external_id): void {
	$this->db->query("REPLACE INTO `" . DB_PREFIX . "mymodule_product` SET `product_id` = '" . (int)$product_id . "', `store_id` = '" . (int)$store_id . "', `external_id` = '" . $this->db->escape($external_id) . "', `date_modified` = NOW()");
}
```

The core's DB class has no prepared statements. So the rule is simple: cast numbers via `(int)` or `(float)`, pass strings through `escape()`, and always wrap them in quotes. Never insert column names or sort direction from user requests directly into SQL. Validate them against an allowlist, as the lists in the core's admin do. More about queries in models is covered in the article [OpenCart model and $this->db](https://opencartcode.com/en/wiki/dev-mvc/opencart-model).

> `REPLACE INTO` in the example is convenient for binding tables with a natural key, but it deletes and re-inserts the row. If the table has columns that this query doesn't pass, they will reset to their default values. In that case, use `INSERT ... ON DUPLICATE KEY UPDATE`.

## How do you avoid leaving garbage when the core deletes a product or order?

When an administrator deletes a product, the core cleans up only its own tables. Your module's rows with this `product_id` will remain forever, and later, when a new product with the same ID appears, they may even "come back to life".

Foreign keys seem like an obvious solution, but with core tables it's better not to use them. **OpenCart 3.0:** core tables use the MyISAM engine, which doesn't support foreign keys. **OpenCart 4.1:** the core uses InnoDB, but a key without `ON DELETE CASCADE` will block product deletion in admin with an SQL error. A cascading key will silently delete the module's rows every time the core deletes the corresponding row in its table, and the module will have no way to influence this.

A more reliable path is an event that fires after deletion:

| Version | Trigger |
| --- | --- |
| OpenCart 3.0 | `admin/model/catalog/product/deleteProduct/after` |
| OpenCart 4.1 | `admin/model/catalog/product.deleteProduct/after` |

In 3.0 the method name is preceded by a slash (`admin/model/catalog/product/deleteProduct/after`), and in 4.1 by a dot (`admin/model/catalog/product.deleteProduct/after`). A trigger with the wrong separator won't fire, and there will be no error. The handler receives the method's arguments, that is `product_id`, and deletes the module's rows. Registering events in `install()` and cleaning them up is described in the article [module install and uninstall](https://opencartcode.com/en/wiki/dev-extensions/install-opencart-module).

Add one more safeguard: when reading, join your table with the core table via `INNER JOIN`, not `LEFT JOIN`. That way "orphaned" rows won't appear in the output, even if someone disabled the event.

## How do you write migrations between module versions?

The core has no migration mechanism for modules, and `install()` is called only during installation. So the module tracks its schema version itself. The working scheme is as follows:

1. Store the current schema version in `setting`, in a separate code path so that the `editSetting()` of the module form doesn't erase it: for example, the code `mymodule_db` and the key `mymodule_db_version`.
2. Describe migration steps as an array of "version → function". Each step must be idempotent: before `ALTER TABLE` it checks whether the column already exists.
3. Call the model's `upgrade()` method from `install()` and from `index()` of the settings form. After updating the files, the administrator almost always opens the form, and the schema catches up with the code.
4. After each successful step, record the new version. That way an interrupted process will continue from where it stopped.

Example

```php
// OpenCart 3.0: admin/model/extension/module/mymodule.php
public function upgrade() {
	$this->load->model('setting/setting');

	$current = (int)$this->model_setting_setting->getSettingValue('mymodule_db_version');

	$steps = array(
		2 => function () {
			if (!$this->hasColumn('mymodule_product', 'price')) {
				$this->db->query("ALTER TABLE `" . DB_PREFIX . "mymodule_product` ADD `price` DECIMAL(15,4) NOT NULL DEFAULT '0.0000'");
			}
		},
		3 => function () {
			$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "mymodule_queue` (`queue_id` INT(11) NOT NULL AUTO_INCREMENT, `payload` TEXT NOT NULL, PRIMARY KEY (`queue_id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
		}
	);

	foreach ($steps as $version => $step) {
		if ($version > $current) {
			$step();

			$this->model_setting_setting->editSetting('mymodule_db', array('mymodule_db_version' => $version));
		}
	}
}

private function hasColumn($table, $column) {
	$query = $this->db->query("SHOW COLUMNS FROM `" . DB_PREFIX . $table . "` LIKE '" . $this->db->escape($column) . "'");

	return (bool)$query->num_rows;
}
```

**OpenCart 4.1:** the logic is the same, but use `getValue()` instead of `getSettingValue()`, which [returns](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#returns) `''` instead of `null`. The `(int)` cast gives zero in both cases. In new installations, `install()` creates the full schema immediately and records the latest version, so migration steps are not run for them.

> An SQL error in a migration throws an exception, and the query text appears in admin. Large `ALTER TABLE` operations on tables with millions of rows can run for minutes and be cut off by the PHP timeout. For such changes, provide a separate button in the settings and state in the instructions that a backup should be made before the update.

## What happens to the tables when a store moves from 3.0 to 4.1?

The module's custom tables are transferred along with the database: names with the store prefix and the data remain. Everything around them changes, so the module version for 4.1 must account for the following:

- **Module code and path.** In 4.1 the module lives in `extension/{папка}/`, and the column `extension` appears in the table `extension`. The module for 4.1 is installed anew, and its `install()` should calmly find the existing tables: `CREATE TABLE IF NOT EXISTS` plus a migration to the current version.
- **Engine.** If the module's tables were created as MyISAM and you plan to use transactions, add the migration step `ALTER TABLE ... ENGINE=InnoDB`.
- **Settings.** Keys like `module_mymodule_status` look the same, but after removing the old module they are gone. If the settings are valuable, provide an import function or move them through migrations before the module is deleted.
- **Events.** 3.0 event records have the old trigger and action format and won't fire in 4.1. The module for 4.1 must delete them with its own code and register them again.

The general structure of modules in the two versions is described in the article [anatomy of an OpenCart extension](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-structure), and updates via Installer in the article [packaging a module into ocmod.zip](https://opencartcode.com/en/wiki/dev-extensions/ocmod-zip).

## Summary

- A custom table is needed for data that grows or changes in the storefront. Keep configuration in `setting`, and don't extend core tables with columns.
- Table name: `DB_PREFIX` plus the module code, InnoDB engine, `utf8mb4_unicode_ci` or the database collation, types and composite keys as in the core.
- In SQL, cast numbers to their type, escape strings, and validate column names against an allowlist.
- Clean up after the core through `deleteProduct/after` events, not through foreign keys on core tables.
- Store the schema version in `setting`, make migrations idempotent, and run them from `install()` and the settings form.

The rest of the topics in this section are collected on the page [creating extensions for OpenCart](https://opencartcode.com/en/wiki/dev-extensions).

## FAQ

**Can a module use transactions?**

Yes, if the module's tables use InnoDB: run START TRANSACTION, COMMIT and ROLLBACK via $this->db->query. In 3.0, core tables on MyISAM do not take part in transactions.

**Should module tables be dropped in uninstall()?**

Only those without valuable data, such as cache and logs. Tables with history or links are better kept, because modules are often removed to reinstall or update them.

**How do I check that a table exists before a query?**

Run SHOW TABLES LIKE with the table name escaped and check num_rows. Do this check in the migration, not in every storefront query.

**Can a migration be run from cron?**

It can, but it is risky: an unfinished ALTER TABLE on a live store locks the table. It is safer to run migrations from the admin panel under the administrator's control.
