Child pages
  • Db class good practices for Prestashop 1.4

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This method automatically generates the insertion or update of the base from a table of data. This method should be used instead of making INSERT or UPDATE requests unless these requests are slightly complex (using SQL functions, intersect queries etc.). The benefit of using one method to do everything is to centralize requests. You can edit this method using PrestaShop’s PrestaShop's 1.4 override system when there is a particular process to apply to tables during insertion..

...

Code Block
$target = Tools::getValue('id');
$name = Tools::getValue('name');
Db::getInstance()->autoExecute(
  'target_table', array(
	'    id_target' =>    (int)$target,
	    'name' =>    => pSQL($name),
  ), 'INSERT');

Requesting this method results in the following SQL query:

...

  • Always ensure that your data is protected before transferring them to autoExecute()
  • In the example, the id_target must be an integer and the name must be protected against SQL injections with pSQL()
  • With PrestaShop, table names must always be preceded with the prefix, included in the constant DB_PREFIX
  • You can generate an UPDATE query by replacing the third argument with UPDATE. In this case, you can bypass SQL restrictions (for example: …->autoExecute(‘table’'table', $data, ‘UPDATE’, ‘myField 'UPDATE', 'myField = 13 AND id < 8’8'); ).

The autoExecuteWithNullValues() method

...

This method is the DELETE version of autoExecute(). It can be used for the same purpose. The $limit argument limits the number of saved items you can delete. The other benefit of this method is that it can be used with PrestaShop’s PrestaShop's SQL query cache system and deletes the cached queries unless the $use_cache argument is false.

...

Code Block
Db::getInstance()->delete(‘target'target_table’table', ‘myField'myField < 15’15', 3);

will generate the following query:

...

Example :

Code Block
$sql = ‘DELETE'DELETE FROM '._DB_PREFIX_.’product'product WHERE date_upd < NOW()';
if (!Db::getInstance()->Execute($sql))
	  die(‘Erreur'Error etc.");

The executeS($sql, $array = true, $use_cache = 1) method

...

Exemple :

Code Block
$sql = ‘SELECT'SELECT * FROM '._DB_PREFIX_.’shop’'shop';
if ($results = Db::getInstance()->ExecuteS($sql))
	  foreach ($results as $row)
		    echo $row[‘id'id_shop’shop'].'::'.$row[‘name’'name'].’<br'<br />’>';

The getRow($sql, $use_cache = 1) method

...

Example :

Code Block
$sql = ‘SELECT'SELECT * FROM '._DB_PREFIX_.’shop'shop
	WHERE id_shop = 42’42';
if ($row = Db::getInstance()->getRow($sql))
	echo $row[‘id'id_shop’shop'].'::'.$row[‘name’'name'];

The getValue($sql, $use_cache = 1) method

...

Example :

Code Block
$sql = ‘SELECT'SELECT COUNT(*) FROM '._DB_PREFIX_.’shop’'shop';
   $totalShop = Db::getInstance()->getValue($sql);

...