DB class best practices
Table of content
/*<![CDATA[*/ div.rbtoc1597308498708 {padding: 0px;} div.rbtoc1597308498708 ul {list-style: disc;margin-left: 0px;} div.rbtoc1597308498708 li {margin-left: 0px;padding-left: 0px;} /*]]>*/
DB class best practices
Most of the time, creating a module or overriding PrestaShop means using or inserting data in the database. Knowing how to properly use the DB core class is therefore mandatory for developers. Besides providing you with an abstraction for other potential database system, the DB class offers several tools to make your life easier.
This page explains the various methods, the contexts in which they should be used, and the development best practices.
At the bottom of the page are the main differences in the DB class between version 1.4 and 1.5 of PrestaShop.
Fundamentals
The DB class is really made of two classes:
The
Db
class, which can found in the/classes/db/Db.php
, and is abstracted.A subclass which extends the
Db
class. Currently, three class abstractions are supported as subclasses: MySQL, MySQLi and PDO. PDO is used by default; however, if the PDO extension is not installed on the server, the MySQLi extension is used instead. And if MySQLi is not installed either, then MySQL is used.
DB is a pseudo-singleton, as it can still be manually instantiated, because its constructor is public. However, within PrestaShop, it is recommended to instantiate it this way:
In some cases, you might encounter this alternative:
If PrestaShop's database user allows the use of MySQL slave servers in its architecture, then this last instance's connection can be done on the slave servers.
You should only use the PS_USE_SQL_SLAVE
argument when making read-only queries (SELECT
, SHOW
, etc.), and only if these do not need a result to be immediately updated with a result. If you make a query on a table right after inserting data in that same table, you should make that query on the master server.
The available methods
insert()
Method signature: insert($table, $data, $null_values = false, $use_cache = true, $type = Db::INSERT, $add_prefix = true)
.
This method was created to automatically generate data insertion in the database, from a data table. It should be used instead of doing INSERT
queries, unless these queries are rather complex (use of SQL functions, nested queries, etc.).
Building every query using one method allows you to centralize your calls. If one day you need to perform a specific processing on some tables during data insertion, you can do so by overloading this method using PrestaShop's overriding system.
Fictitious example:
Triggering this code generates the following SQL query:
Make sure that your data is always checked and protected when doing an insertion. In our example, we want to make sure that we do have an integer with an explicit (int)
cast, and that the name is protected against SQL injections thanks to the pSQL()
method.
Method parameters
update()
Method signature: update($table, $data, $where = '', $limit = 0, $null_values = false, $use_cache = true, $add_prefix = true)
This method works as the insert()
method does, but for data update (UPDATE
queries). Both have roughly the same parameters, with type
gone and these two additions:
delete()
Method signature: delete($table, $where = '', $limit = 0, $use_cache = true, $add_prefix = true)
.
This method is an equivalent to insert()
and update()
, only for DELETE
queries. You should use it for the same reasons.
The $limit
parameter enables you to limit the number of records to that you wish to delete. The other advantage of this method is that it will be used by PrestaShop's SQL queries cache system, and will therefore delete the affected queries in cache, unles the $use_cache
is false
.
Example:
...will generate the following query:
execute()
Method signature: execute($sql, $use_cache = 1)
.
This method executes the given SQL query. It should only be used for 'write' queries (INSERT
, UPDATE
, DELETE
, TRUNCATE
, etc.), because it also deletes the query cache (unles $use_cache
is set to false
).
Example:
You should use insert()
, update()
and delete()
as much as possible, and only use execute()
if the query gets too complex.
Please note that this method returns a boolean value (true
or false
), not a database resource that can then be used.
query()
Method signature: query($sql)
.
All the method of the DB classes that make SQL query use the query()
as the common, low-level method. It does the same as the execute()
method, with two exceptions:
No cache control management.
Will not return a boolean; instead returns a database resource that you can use with other DB class methods, such as
nextRow()
.
executeS()
Method signature: executeS($sql, $array = true, $use_cache = 1)
.
This method executes a given SQL query, and makes that whole resulting data available through a multidimensional array. It should only be used for 'read' queries (SELECT
, SHOW
, etc.). The query's results are cached, unless the $use_cache
parameter is set to false
. The second parameter, $array()
, is deprecated and should not be used, leave it as true
.
Example:
getRow()
Method signature: getRow($sql, $use_cache = 1)
.
This method executes a given SQL query and retrieves the first row of results. It should only be used with 'read' queries (SELECT
, SHOW
, etc.). The query's results are cached, unless the $use_cache
parameter is set to false
.
This method automatically adds a LIMIT clause to the query. Be careful not to add one manually.
Example:
getValue()
Method signature: getValue($sql, $use_cache = 1)
.
This method executes a given SQL query and retrieves the first value of the first row of results. It should only be used with 'read' queries (SELECT
, SHOW
, etc.). The query's results are cached, unless the $use_cache
parameter is set to false
.
This method automatically adds a LIMIT clause to the query. Be careful not to add one manually.
Example:
getValue()
does not protect your code from hacking attempts (SQL injections, XSS flaws and CRSF breaches). You still have to secure your data yourself.
One PrestaShop-specific securization method is pSQL($value)
: it helps protect your database against SQL injections.
NumRows()
This method caches and returns the number of results from the most recent SQL query;
This method has not yet been deprecated, but it is still not recommended to use for best-practices reasons. Indeed, it is better to retrieve the number of results using a SELECT COUNT (*)
before.
A few other methods
Insert_ID()
: returns the ID created during the latestINSERT
query.Affected_Rows()
: returns the number of lines impacted by the latestUPDATE
orDELETE
query.getMsgError()
: returns the latest error message, if the query has failed.getNumberError()
: returns the latest error number, if the query has failed.
Changes between PrestaShop 1.4 and 1.5
The
autoExecute()
andautoExecuteWithNullValues()
are deprecated. You should replace them withinsert()
andupdate()
, respectively.The table prefix is no longer mandatory for the
delete()
method.The
execute()
method does not return a SQL resource but a boolean value. Usequery()
to get a resource.PDO and MySQLi support.
Last updated