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
MVC-L: controllers, models, templates

OpenCart Model: Database Queries via $this->db in 3.0 and 4.1

How the OpenCart model works: file and class, loading from a controller, $this->db methods, safe queries, getLastId, caching, and differences between 3.0 and 4.1.

15 min read OC 3.0 OC 4.1

The OpenCart model is a PHP class that handles all database work. The controllerCode that receives a request and prepares data. More in the glossary → calls model methods, and the model builds SQL and runs it through $this->db->query(). Below we cover how to name and place a model, how to load it, what the $this->db object can do, how to write safe queries, and how OpenCart 3.0 and 4.1 differ. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling work differently.

Where does the model live and how do you name the class?

In the MVC-L scheme, the model is the only place where SQL should appear. The article how the controller, model, template and language are connected describes the overall picture. The model file path uniquely determines the class name. An error in the path or class name ends in a fatal error. In 3.0, "Could not load model" means there is no file at that route. If the file exists but the class is named incorrectly, you get a different fatal error (class not found). Letter case in the class name does not matter.

OpenCart 3.0: files are located in catalog/model/ (storefrontWhat the customer sees: the home page, categories, product page, and cart. More in the glossary →) or admin/model/ (admin). The class does not use namespaces. The name consists of the Model prefix and path parts in CamelCase: file catalog/model/catalog/product.php contains class ModelCatalogProduct. Extension models are placed in admin/model/extension/module/my_module.php, and the class for such a file is ModelExtensionModuleMyModule.

OpenCart 4.1: classes use namespaces. The built-in product model is declared as namespace Opencart\Catalog\Model\Catalog; with class Product, which extends \Opencart\System\Engine\Model. ExtensionsAdditional functionality: a module, a payment or shipping method, a feed, or a theme. They are managed in "Extensions → Extensions." More in the glossary → live separately, in extension/<назва>/. The model of the my_module module for admin is located in extension/my_module/admin/model/module/my_module.php and has the namespace Opencart\Admin\Model\Extension\MyModule\Module. The full directory map is in the article file structure of OpenCart 3.0 and 4.1.

WhatOpenCart 3.0OpenCart 4.1
Module model fileadmin/model/extension/module/my_module.phpextension/my_module/admin/model/module/my_module.php
ClassModelExtensionModuleMyModule extends ModelMyModule extends \Opencart\System\Engine\Model in namespace
Route for loadingextension/module/my_moduleextension/my_module/module/my_module
Property in controller$this->model_extension_module_my_module$this->model_extension_my_module_module_my_module
DB connection check methodconnected() (calls a non-existent adapter method, better not to call)isConnected()

How do you load a model and call its method?

You don't create the model through new. It is loaded by the Loader: $this->load->model('catalog/product'). After that, an object with the key model_catalog_product appears in the registry, that is, the route with slashes replaced by underscores. Through the controller's magic __get, this object is available as $this->model_catalog_product. The details of the mechanism are described in the articles about how load->model and load->controller work and about the Registry and access to objects.

// Контролер (3.0 і 4.1 однаково)
$this->load->model('catalog/product');

$product_info = $this->model_catalog_product->getProduct($product_id);

The model extends the base class Model, so it has access to the same registry services as the controller: $this->db, $this->config, $this->cache, $this->session. Inside a model you can also load other models. However, taking data from $this->request inside a model is bad practice. The controller should pass parameters, so the model stays predictable and can be called from cron, an API, or another module.

The Loader does not return a "bare" object. Method calls to the model go through a proxy, and the core can fire events around them. The trigger format depends on the version. In a module event, the trigger is written with the application prefix. In 3.0, the method is preceded by a slash: catalog/model/catalog/product/getProduct/before and .../after. In 4.1 there is a dot: catalog/model/catalog/product.getProduct/before and .../after. The core discards the catalog/ or admin/ prefix when loading the events of the corresponding application, so without it the module event will not fire. A trigger with the wrong separator simply won't fire, and there will be no error. The way to change the result also differs. In 3.0, the value returned by the handler replaces the method's result. Any return from before, except null and Exception (including false or ''), skips the method call and becomes its result. In 4.1, the returned value is ignored, and only arguments passed by reference (&$args, &$output) can be changed. This is how modules change the behavior of standard models without editing files. So be aware: if your method's result differs from what you expect, it may have been changed by someone else's event.

flowchart TD
  A["Controller"] --> B["load->model('catalog/product')"]
  B --> C["Registry: model_catalog_product"]
  C --> D["before event"]
  D --> E["Model method builds SQL"]
  E --> F["$this->db->query()"]
  F --> G["mysqli adapter"]
  G --> H["Result: row / rows / num_rows"]
  H --> I["after event"]
  I --> A

What can $this->db do and what does query() return?

The DB class is a thin wrapper over the adapter. The adapter name and connection parameters are taken from config.php (DB_DRIVER, DB_HOSTNAME, etc.); more on this in the article about OpenCart file configs. By default it is mysqli. There are only a few public methods:

system/library/db.php · OpenCart 3.0.5.1 · lines 44–57

	public function query($sql) {
		return $this->adaptor->query($sql);
	}

	/**
     * 
     *
     * @param	string	$value
	 * 
	 * @return	string
     */
	public function escape($value) {
		return $this->adaptor->escape($value);
	}

In 4.1 the set of methods is the same, but types have been added:

system/library/db.php · OpenCart 4.1.0.4 · lines 53–66

	public function query(string $sql) {
		return $this->adaptor->query($sql);
	}

	/**
	 * Escape
	 *
	 * @param string $value Value to be protected against SQL injections
	 *
	 * @return string Returns escaped value
	 */
	public function escape(string $value): string {
		return $this->adaptor->escape($value);
	}
  • query($sql): for SELECT it returns an object with three properties. num_rows is the number of rows, row is the first row as an associative array (or an empty array), rows is all rows. For INSERT/UPDATE/DELETE the mysqli adapter returns true. If the query is faulty, the adapter throws an exception with the MySQL error text and the SQL itself.
  • escape($value) escapes a string for insertion inside quotes.
  • getLastId() returns the auto-increment ID after INSERT.
  • countAffected() returns the number of rows changed by the last query.
  • connected() in 3.0 formally exists, but it calls the adapter method connected(), which does not exist: the mysqli and pgsql adapters have isConnected(). Therefore a direct call to $this->db->connected() in 3.0 ends with a fatal error, and there is effectively no working connection check through the DB wrapper there. In 4.1 the correct method is isConnected().

The constant DB_PREFIX contains the table prefixThe beginning of table names, by default oc_. More in the glossary →, by default oc_. Always use it in every query and never hardcode oc_. A telling example: in core 4.1.0.4, the getProducts() method in the filter branch contains a hardcoded `oc_product` (line 118). On a store with a different prefix, this query fails. If you migrate a database with a prefix other than oc_, check category filtering.

How do you write safe queries without SQL injection?

OpenCart's DB wrapper does not provide prepared statements. Protection relies on discipline, and standard models follow three rules. Violating any of them is the most common cause of breaks caused by third-party modules. General security tips for the admin panel are collected in the article about OpenCart admin security.

  1. Cast numbers to their type. IDs, quantities, statuses are always cast to (int), prices to (float). Even inside quotes: WHERE product_id = '" . (int)$product_id . "'.
  2. Escape strings and wrap them in quotes. Write '" . $this->db->escape($name) . "'. escape() alone without quotes does not protect.
  3. Check identifiers against a whitelist. A column name or sort direction cannot be escaped, so they are compared against an allowed list.

Here is how the third rule is implemented in the standard product model:

catalog/model/catalog/product.php · OpenCart 3.0.5.1 · lines 168–184

		if (isset($data['sort']) && in_array($data['sort'], $sort_data)) {
			if ($data['sort'] == 'pd.name' || $data['sort'] == 'p.model') {
				$sql .= " ORDER BY LCASE(" . $data['sort'] . ")";
			} elseif ($data['sort'] == 'p.price') {
				$sql .= " ORDER BY (CASE WHEN special IS NOT NULL THEN special WHEN discount IS NOT NULL THEN discount ELSE p.price END)";
			} else {
				$sql .= " ORDER BY " . $data['sort'];
			}
		} else {
			$sql .= " ORDER BY p.sort_order";
		}

		if (isset($data['order']) && ($data['order'] == 'DESC')) {
			$sql .= " DESC, LCASE(pd.name) DESC";
		} else {
			$sql .= " ASC, LCASE(pd.name) ASC";
		}

For LIMIT, the core casts start and limit to (int). For an ID list in IN (...), each element is passed separately through (int), and then the array is joined with implode. This technique is worth copying.

How do you write a module model: table, insert, select

Let's look at a typical set for a module that stores its own records, for example "Call me back" requests. The table is created in the install() method of the model. The module's controller calls it when the administrator clicks "Install" on the "Extensions → Extensions" page after selecting "Modules" in the extension type list. When the module is deleted, uninstall() is called accordingly.

Extensions → Extensions, type «Modules»: the Install button runs the module model's install(), which creates the table
Extensions → Extensions, type "Modules": the Install button runs the module model's install(), which creates the table · OpenCart 4.1.0.4

OpenCart 3.0

<?php
// admin/model/extension/module/callback.php
class ModelExtensionModuleCallback extends Model {
	public function install() {
		$this->db->query("CREATE TABLE IF NOT EXISTS `" . DB_PREFIX . "callback` (
			`callback_id` INT(11) NOT NULL AUTO_INCREMENT,
			`name` VARCHAR(64) NOT NULL,
			`telephone` VARCHAR(32) NOT NULL,
			`status` TINYINT(1) NOT NULL DEFAULT '0',
			`date_added` DATETIME NOT NULL,
			PRIMARY KEY (`callback_id`)
		) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
	}

	public function uninstall() {
		$this->db->query("DROP TABLE IF EXISTS `" . DB_PREFIX . "callback`");
	}

	public function addCallback($data) {
		$this->db->query("INSERT INTO `" . DB_PREFIX . "callback` SET `name` = '" . $this->db->escape($data['name']) . "', `telephone` = '" . $this->db->escape($data['telephone']) . "', `date_added` = NOW()");

		return $this->db->getLastId();
	}

	public function getCallbacks($start = 0, $limit = 20) {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "callback` ORDER BY `date_added` DESC LIMIT " . (int)$start . "," . (int)$limit);

		return $query->rows;
	}
}

The collation utf8mb4_unicode_ci matches the collation of core tables in 3.0.5.1 and 4.1.0.4. You can also omit COLLATE, and then the table will take the database collation. Keep in mind that in 3.0.4.1 the core tables have utf8 / utf8_general_ci. A JOIN on text fields between them and the utf8mb4 table will produce the error "Illegal mix of collations", while a JOIN on numeric IDs works.

OpenCart 4.1

The logic does not change. Namespaces, argument and return types are added, along with the style accepted in the core, with backticks around each identifier:

<?php
// extension/callback/admin/model/module/callback.php
namespace Opencart\Admin\Model\Extension\Callback\Module;
class Callback extends \Opencart\System\Engine\Model {
	public function addCallback(array $data): int {
		$this->db->query("INSERT INTO `" . DB_PREFIX . "callback` SET `name` = '" . $this->db->escape((string)$data['name']) . "', `telephone` = '" . $this->db->escape((string)$data['telephone']) . "', `date_added` = NOW()");

		return $this->db->getLastId();
	}

	public function getCallback(int $callback_id): array {
		$query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "callback` WHERE `callback_id` = '" . (int)$callback_id . "'");

		return $query->row;
	}
}

Pay attention to the return contract: OpenCart 3.0 returns getProduct() from false if the product is not found, while OpenCart 4.1 returns an empty array []:

catalog/model/catalog/product.php · OpenCart 4.1.0.4 · lines 69–81

		if ($query->num_rows) {
			$product_data = $query->row;

			$product_data['variant'] = $query->row['variant'] ? json_decode($query->row['variant'], true) : [];
			$product_data['override'] = $query->row['override'] ? json_decode($query->row['override'], true) : [];
			$product_data['price'] = (float)($query->row['discount'] ?: $query->row['price']);
			$product_data['rating'] = (float)$query->row['rating'];
			$product_data['reviews'] = (int)$query->row['reviews'] ? $query->row['reviews'] : 0;

			return $product_data;
		} else {
			return [];
		}

The if ($product_info) check in the controller works for both variants. But if ($product_info !== false) in 4.1 will let an empty array through, and then accessing keys will produce a warning. For your own models in 4.1, follow the same rule as the core: always return an array, without false.

How do you avoid overloading the database: cache and N+1

Standard 3.0 models have a well-known antipattern. getProducts() first selects only IDs, and then calls getProduct() separately for each row. For 100 products on a page, that results in 101 queries, and each contains several subqueries:

catalog/model/catalog/product.php · OpenCart 3.0.5.1 · lines 200–206

		$query = $this->db->query($sql);

		foreach ($query->rows as $result) {
			$product_data[$result['product_id']] = $this->getProduct($result['product_id']);
		}

		return $product_data;

In OpenCart 4.1, the model selects all fields in one query and caches the result by SQL hash:

catalog/model/catalog/product.php · OpenCart 4.1.0.4 · lines 257–269

		$key = md5($sql);

		$product_data = $this->cache->get('product.' . $key);

		if (!$product_data) {
			$query = $this->db->query($sql);

			$product_data = $query->rows;

			$this->cache->set('product.' . $key, $product_data);
		}

		return $product_data;

For your own models, this leads to several practical conclusions:

  • Don't run a query inside a loop where you can do a single WHERE id IN (...) or JOIN.
  • Cache heavy, rarely changing selections (reference data, "New arrivals" blocks, aggregates) through $this->cache. The key must include everything the result depends on: language, store, customer groupA segment of buyers (retail, wholesale) with different prices and terms. More in the glossary →. This is done in getLatestProducts() in 3.0.
  • After a write, clear the cache, otherwise customers will see stale data. With the file driver, $this->cache->delete('product') deletes all product.* keys. The memcached, redis and mem drivers delete only the exact product key.
  • Add indexes on the columns WHERE and JOIN in your tables, because CREATE TABLE without indexes is a typical cause of slow modules.

How cache drivers work and where files physically reside is explained in the articles about session and cache in OpenCart and about the storage directory. If the problem is overall storefront speed rather than a single query, page-level caching and PageSpeed optimization are covered in the review of the Jet Cache module.

Common errors and how to debug them

When a query fails, the adapter throws an exception. The MySQL error text together with the number and the full SQL is written to the log: "System → Maintenance → Error Logs". Start searching there. Copy the SQL from the log and run it in phpMyAdmin; that will immediately show which column or table does not exist.

Error log: here you can see the MySQL error text and the SQL query that failed
Error log: here you can see the MySQL error text and the SQL query that failed · OpenCart 4.1.0.4
  • "Call to a member function … on null": the model is not loaded or the property is named incorrectly. Check the route and the name of model_…, especially for 4.1 extensions, where the module name appears in the path twice.
  • "Could not load model": in 3.0 there is no file at the route, so check the route against the file path. If the file exists but the class is named incorrectly, you get a different fatal error (class not found). Letter case in the class name does not matter. In 4.1 this exception occurs when the class is not found in the namespace, so check the namespace and class name.
  • Table not found: you forgot DB_PREFIX, or the module was not reinstalled after an update, so install() did not run.
  • Garbled text instead of Cyrillic: the connection encoding does not match the data encoding, or the table was created with latin1. Cyrillic is stored normally in both utf8 and utf8mb4, so specify the encoding explicitly in CREATE TABLE. Emoji in 3.0 won't be saved even in an utf8mb4 table, because the connection works in utf8. In 4.1 the connection is already utf8mb4.
  • Empty result where data exists: standard queries filter by language_id and store_id. Check whether there is a description in the required language and whether the product is assigned to the store.
  • A 3.0 module breaks on 4.1: a call to connected() instead of isConnected(), a check for false instead of an empty array, escape() with null.

How data from the model then gets into the template is described in the article about the controller, data and child controllers.

Summary

  • An OpenCart model is a class where all the SQL is concentrated. The file path determines the class name: in 3.0 it is CamelCase with the Model prefix, in 4.1 it is a namespace.
  • Models are loaded via $this->load->model('route') and called as $this->model_route_with_underscores. Calls pass through events, so other modules can change them.
  • $this->db has only query, escape, getLastId, countAffected and a connection check. Security depends on you: (int) for numbers, escape in quotes for strings, a whitelist for sorting.
  • Always use DB_PREFIX, avoid queries in loops, cache heavy selections and clear the cache after writes.
  • When porting a module from 3.0 to 4.1, check the types, escape() with null, the [] return instead of false, and isConnected().

Next, it is worth understanding how the controller passes data from the model to the Twig template and how the route finds the controller. These topics are collected in the section MVC-L: controllers, models, templates, and routing is discussed in detail in the article about route= routing in 3.0 and 4.1.

FAQ

Can I run SQL directly in a controller via $this->db?
Technically yes, since $this->db is also available in a controller. But you lose code reuse and the ability to intercept model calls with events. Move the query into a model, even if it's only one line.
How do I connect to a second database, for example a warehouse one?
Create a separate object new DB(...) with the required parameters (in 4.1, the \Opencart\System\Library\DB class) and, if needed, register it in the registry under your own key, for example db_stock. Leave the main $this->db untouched.
Does OpenCart support prepared statements?
The DB wrapper in 3.0 and 4.1 doesn't provide them; the query() method accepts only a ready SQL string. For security, rely on type casting, escape() and allowlists.
How do I override a standard model method without editing core files?
Register an event on the trigger model/catalog/product/getProduct/after and modify the result in your handler. The alternative is modifying OCMOD, but events are more resilient to updates.
Why does the storefront show old data after I change a product in the admin?
Most often the cache is to blame: the standard cache in 4.1 for getProducts or a third-party module's cache. Clear the cache and make sure your code calls $this->cache->delete with the right prefix after writing.
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.