# SQL queries in OpenCart without injection: escape, (int) and allowlists in 3.0 and 4.1

> How to write safe SQL queries in OpenCart 3.0 and 4.1 modules: what $this->db->escape() actually does, where (int) is needed, and how to protect ORDER BY and LIKE.

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

Safe **SQL queries in [OpenCart](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#opencart)** rest on three rules: numbers are cast to a type with `(int)` or `(float)`, strings are passed through `$this->db->escape()` and wrapped in single quotes, and column names, sort direction, and other SQL parts that cannot be escaped are taken only from a whitelist. The core provides no prepared statements with parameters through `$this->db`, so these rules are not a formality but the only protection.

Below is what the DB class does in 3.0 (3.0.4.1 and 3.0.5.1) and 4.1 (4.1.0.4), how the `mysqli` and `pdo` drivers differ, and which details lead modules to SQL injection or a fatal error. Examples are for OpenCart 4.1; in 4.0.x, model triggers and event handling differ.

## What $this->db can do, and why there is no prepare?

In a model you work with an object of the `DB` class (`system/library/db.php`), which only passes calls to the driver from `system/library/db/`. The driver is chosen by the `DB_DRIVER` constant in `config.php`; the installer of both branches offers `mysqli` and `pdo`, and most stores use `mysqli`. How a model gets `$this->db` is described in the article about the [OpenCart model and queries via $this->db](https://opencartcode.com/en/wiki/dev-mvc/opencart-model).

| Method | OpenCart 3.0 | OpenCart 4.1 |
| --- | --- | --- |
| Run a query | `query($sql)` | `query(string $sql)` |
| Escape a string | `escape($value)` | `escape(string $value): string` |
| Affected rows | `countAffected()` | `countAffected(): int` |
| Last id | `getLastId()` | `getLastId(): int` |
| Connection check | `connected()` | `isConnected(): bool` |

The `query()` wrapper in both branches accepts **only an SQL string**. In 3.0 the `pdo` driver has its own `prepare()`, `bindParam()` and `query($sql, $params)`, but the DB class does not pass them through, so they cannot be reached from a model. The `mysqli` driver in both branches simply passes the string to `mysqli::query()`. So everything that goes into SQL is concatenated by you, and responsibility for every variable is yours.

```mermaid
flowchart TD
  A["Data from request, DB, API"] --> B{"What kind of value is it?"}
  B -->|"Number"| C["(int) or (float)"]
  B -->|"String"| D["escape() in quotes"]
  B -->|"Column, ASC/DESC"| E["Whitelist"]
  B -->|"List of ids"| F["array_map intval + implode"]
  C --> G["SQL string"]
  D --> G
  E --> G
  F --> G
  G --> H["$this->db->query()"]
```

## How to protect numbers: (int), (float) and lists of ids

The OpenCart core almost everywhere writes numbers like this: `product_id = '" . (int)$product_id . "'`. Type casting is the simplest and most reliable protection: after `(int)` only an integer reaches the SQL, whatever arrives in GET. The core puts quotes around numbers out of habit; MySQL compares `'15'` correctly with an INT column, so you can write it with or without quotes.

Example

```php
$product_id = (int)($this->request->get['product_id'] ?? 0);
$price      = (float)($this->request->post['price'] ?? 0);

$this->db->query("UPDATE `" . DB_PREFIX . "product`
	SET `price` = '" . $price . "'
	WHERE `product_id` = '" . $product_id . "'");
```

The most common hole in modules is a list of ids in `IN (...)`. An array from a form or AJAX is glued together with `implode(',', $ids)`, and any string from the array goes into the SQL as is. The correct approach is to cast each element and handle an empty list separately, because `IN ()` is a syntax error:

Example

```php
$ids = array_filter(array_map('intval', (array)($this->request->post['selected'] ?? [])));

if ($ids) {
	$this->db->query("DELETE FROM `" . DB_PREFIX . "mymodule_item`
		WHERE `item_id` IN (" . implode(',', $ids) . ")");
}
```

For `LIMIT` and `OFFSET` quotes do not work at all: MySQL does not accept a string there. Use only `(int)` and boundary checks, as the core does in `getProducts()`: a negative start becomes zero, and a limit less than one is replaced with the default.

## How does escape() work, and where does it not save you?

In the `mysqli` driver, the `escape()` method is the `real_escape_string()` connection function. It escapes quotes, backslashes and control characters according to the connection's character set, but it **does not add quotes**: you have to add them yourself.

OpenCart 3.0.5.1

OpenCart 4.1.0.4

`system/library/db/mysqli.php` · OpenCart 3.0.5.1 · lines 53–55

```php
	public function escape($value) {
		return $this->connection->real_escape_string(($value===null) ? '' : $value);
	}
```

`system/library/db/mysqli.php` · OpenCart 4.1.0.4 · lines 133–135

```php
	public function escape(string $value): string {
		return $this->connection->real_escape_string($value);
	}
```

The difference in signature matters in practice. **OpenCart 3.0:** `null` becomes an empty string. **OpenCart 4.1:** the parameter is typed as `string`, so `escape(null)` or `escape($array)` fails with `TypeError`. When a value may be missing, cast it explicitly: `$this->db->escape((string)($data['name'] ?? ''))`. The 4.1 core also writes `escape((string)$data[...])` everywhere.

### Where escape does not help

- **Without quotes.** `WHERE code = " . $this->db->escape($code)` protects nothing: the attacker does not need to close a quote, it is enough to append `1 OR 1=1`.
- **For column names and keywords.** Escaping does not turn `name; DROP` into a safe column name. A whitelist is needed here (next section).
- **For LIKE patterns.** escape does not touch the `%` and `_` characters from user input, they work as a pattern. This is not injection, but a search by `%` will return the whole table; if that is undesirable, escape them separately with `addcslashes($value, '%_')`.

### htmlspecialchars in Request is not SQL protection

The `Request` class in both branches runs GET, POST and cookie data through `htmlspecialchars(..., ENT_COMPAT, 'UTF-8')`. The `ENT_COMPAT` flag converts double quotes to `&quot;`, but **leaves single quotes as they are**. OpenCart uses single quotes in SQL, so the idea that "request data is already clean" is a false sense of security. Escape is always needed.

## ORDER BY, column names and direction: whitelist only

Sorting in admin and [storefront](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#storefront) lists comes from GET (`sort=pd.name&order=DESC`), and it cannot be substituted through escape or `(int)`. In `getProducts()` of both branches the core solves this with an `$sort_data` array: the `sort` value is accepted only if it is in the array (`in_array()`), otherwise the default sort is used. The direction is not taken from the request either: if `order` equals `DESC`, `DESC` is written into the SQL, otherwise `ASC`.

Example

```php
$sort_data = [
	'name'       => 'i.name',
	'date_added' => 'i.date_added',
	'status'     => 'i.status'
];

$sort  = $sort_data[$data['sort'] ?? ''] ?? 'i.date_added';
$order = (($data['order'] ?? '') === 'ASC') ? 'ASC' : 'DESC';

$sql .= " ORDER BY " . $sort . " " . $order;
```

Here the array key is what arrives in the URL, and the value is the real column. The user never sees or sets the column name directly, so even a schema change does not break links. The same rule applies to any dynamic part of SQL: the module's table name for different types, filter fields, aggregate functions. If a value is not from the whitelist, the query is not built.

> The same applies to table names in your own code. Do not build `DB_PREFIX . $this->request->get['type']`; make an array of allowed types and take the name from it. For designing module tables, see the article [custom module tables in OpenCart](https://opencartcode.com/en/wiki/dev-extensions/opencart-module-tables).

## The PDO driver in 4.1: why escape returns ":0"

**OpenCart 4.1** with the `pdo` driver works differently than with `mysqli`. Its `escape()` does not escape the string, but puts the value into an internal parameter array and returns a placeholder like `:0` or `:1`. Before execution, the `query()` method replaces the **placeholder in single quotes** (`':0'`) with a named parameter using a regular expression, calls `prepare()` and `execute()` with the accumulated values, and then clears the array. So this is a real prepared statement, but only if you write it the same way the core does.

This leads to restrictions that are invisible on `mysqli` and break on `pdo`:

- **The escape value must be entirely inside quotes.** `LIKE '%" . $this->db->escape($word) . "%'` gives `'%:0%'` in the SQL, the placeholder is not recognized, and the query searches for the literal string ":0". The 4.1 core writes `LIKE '" . $this->db->escape('%' . $word . '%') . "'`, with the percent signs inside escape. Write it the same way: on `mysqli` the result is the same.
- **Do not use the result of escape outside SQL**, for example in cache keys, logs or comparisons. On PDO it will be a placeholder, not text.
- **Call escape for the query you are running right away.** Values accumulate until the nearest `query()`; if you prepare fragments for two queries in advance, the second one gets someone else's parameters.

**OpenCart 3.0** with the `pdo` driver does not do this: there `escape()` is the `str_replace()` function for [special](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#special) characters, with no preparation. So for 3.0 the rules are the same as for `mysqli`, but do not rely on the quality of this replacement: still cast numbers to a type.

## Query errors: how not to show SQL to visitors

Both `mysqli` drivers throw an exception on error, and its text includes the **full SQL query**.

`system/library/db/mysqli.php` · OpenCart 4.1.0.4 · lines 121–123

```php
		} catch (\mysqli_sql_exception $e) {
			throw new \Exception('Error: ' . $this->connection->error . '<br/>Error No: ' . $this->connection->errno . '<br/>' . $sql);
		}
```

In 3.0.5.1 the same thing is done by checking `errno` after the query (lines 48–50). If error display is enabled in the settings, this text with table names, prefix and query structure will be visible to anyone who finds a "bad" parameter. For an attacker this is a ready map for injection. On a live store, turn off error display in System → Settings, Server tab, Display Errors switch; keep the [error log](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#error-log) enabled.

Server tab: turn off error display on a live store, keep the log · OpenCart 4.1.0.4

Two more habits that reduce the damage:

- Check permissions and the token before building a query: admin AJAX methods without a `user_token` check and without permission checks are the shortest path to injection on behalf of an administrator. For details, see the articles on [user_token in the admin](https://opencartcode.com/en/wiki/dev-mvc/opencart-user-token) and [module access permissions](https://opencartcode.com/en/wiki/dev-mvc/opencart-module-access-permissions).
- Validate input already in the [controller](https://opencartcode.com/en/wiki/glossary/e-commerce-glossary#controller): length, format, allowed values. The validation scheme for a module form is described in the article on the [module settings form](https://opencartcode.com/en/wiki/dev-extensions/module-settings-form-opencart).

General measures for protecting the control panel are collected in the blog: [OpenCart admin security](https://opencartcode.com/en/blog/bezpeka-adminki-opencart-zaxist-paneli-vid-zlamu).

## How to store arrays, JSON and dates

Modules often write complex values into their own tables: block settings, lists of ids, filter conditions. Convert the array to a string with `json_encode()` first, and only then pass the string through escape in quotes. The 4.1 core does the same with serialized settings in the `setting` table: an array value is encoded as JSON, and the `serialized` field marks that it must be decoded when read. Do not insert JSON without escape on the grounds that "PHP generated it": it may contain single quotes from user text.

Example

```php
$conditions = json_encode($data['conditions'] ?? [], JSON_UNESCAPED_UNICODE);

$date = (string)($data['date_end'] ?? '');

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
	$date = '0000-00-00';
}

$this->db->query("INSERT INTO `" . DB_PREFIX . "mymodule_rule` SET
	`conditions` = '" . $this->db->escape($conditions) . "',
	`date_end` = '" . $this->db->escape($date) . "',
	`date_added` = NOW()");
```

Check dates from forms by format before SQL: escape protects against injection, but not against MySQL receiving "32.13.2026" and, in non-strict mode, storing a zero date. Remember that the `mysqli` driver in both branches opens the session with `sql_mode = 'NO_ZERO_IN_DATE,NO_ENGINE_SUBSTITUTION'`, meaning without `STRICT_TRANS_TABLES`: invalid values often produce no error but are silently truncated. So validation in code matters more than it seems from experience with other frameworks.

## Summary

- Because of `$this->db` there are no prepared statements with parameters: you concatenate the SQL yourself, and every variable must pass one of three filters.
- Numbers and `LIMIT`: `(int)`/`(float)`; lists of ids: `array_map('intval')` plus a check for an empty array.
- Strings: `escape()` and always in single quotes. In 4.1 pass only `string`, because `null` gives `TypeError`.
- Build a LIKE pattern inside escape (`escape('%' . $word . '%')`), otherwise the search breaks on the `pdo` driver in 4.1.
- Columns, sort direction and table names come only from a whitelist, like `$sort_data` in the core.
- `htmlspecialchars` in Request does not protect against a single quote, and showing errors on a live store exposes SQL.

Next, review your models by searching for `request->get`, `request->post` and `implode(`: these are three places where unescaped values most often hide. Other articles in the section are on the [OpenCart Database](https://opencartcode.com/en/wiki/dev-database) page.

## FAQ

**Can you use your own PDO connection with prepare in an OpenCart module?**

Technically yes, the constants DB_HOSTNAME, DB_USERNAME and others are available from config.php. But it's a second connection with different session settings, so for regular queries it's simpler to follow the rules of escaping and type casting.

**Do you need to escape data that the module itself read from the database?**

Yes. The value could have gotten into the table through a customer form, an import or an API, so when it is inserted into SQL again, it is just as dangerous as data from GET.

**Does (int) protect against everything if the id comes in as the string “15abc”?**

Yes, PHP will convert it to 15, so only a number reaches the SQL. But it may point to a different record, so in the controller it's better to check that the value really consists of digits.

**How do you check which database driver the store uses?**

Look at the DB_DRIVER constant in config.php of the catalog and admin. The value mysqli or pdo determines how escape() behaves.
