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 → moduleA block on a page: a slideshow, popular products, a filter. It is placed through layouts. More in the glossary → 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.
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 storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary → is running, for example counters, queues or cache;
- other entities are linked to the record: productA catalog item with a name, price, description, and photos. More in the glossary →, 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
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 hasDECIMAL(15,4), like thepricecolumn inproduct. This wayJOINand comparisons work without casts. - Composite key for languages and stores. The core does the same:
product_descriptionhas 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_cior don't specifyCOLLATEat all, so the table takes the database collation. Theutf8mb4_general_cicomparison is not used by the core: in 3.0.4.1 core tables useutf8/utf8_general_ci, and in 3.0.5.1 and 4.1 they useutf8mb4/utf8mb4_unicode_ci. If the store was moved or changed manually, check its table collation viaSHOW TABLE STATUSand use the same one. Mismatched collations cause the "Illegal mix of collations" error inJOINon 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
DEFAULTfor 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 withoutDEFAULTa non-obvious empty value will end up there. Besides, a migration can add a new column withDEFAULTto 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
// 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.
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/ |
| OpenCart 4.1 | admin/ |
In 3.0 the method name is preceded by a slash (admin/), and in 4.1 by a dot (admin/). 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.
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:
- Store the current schema version in
setting, in a separate code path so that theeditSetting()of the module form doesn't erase it: for example, the codemymodule_dband the keymymodule_db_version. - Describe migration steps as an array of "version → function". Each step must be idempotent: before
ALTER TABLEit checks whether the column already exists. - Call the model's
upgrade()method frominstall()and fromindex()of the settings form. After updating the files, the administrator almost always opens the form, and the schema catches up with the code. - After each successful step, record the new version. That way an interrupted process will continue from where it stopped.
Example
// 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 returnsProcessing a customer's refusal of a product. It has its own statuses and reasons. More in the glossary → '' 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.
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{папка}/ extensionappears in the tableextension. The module for 4.1 is installed anew, and itsinstall()should calmly find the existing tables:CREATE TABLE IF NOT EXISTSplus 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_statuslook 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, and updates via Installer in the article packaging a module into 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_PREFIXplus the module code, InnoDB engine,utf8mb4_unicode_cior 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/afterevents, not through foreign keys on core tables. - Store the schema version in
setting, make migrations idempotent, and run them frominstall()and the settings form.
The rest of the topics in this section are collected on the page creating extensions for OpenCart.