Matteo Enna
Matteo Enna

Reputation: 1301

PrestaShop, get ID when insert in DB

I am creating a script for PrestaShop 1.6 that inserts data into a table. My table is made in this way:

As I enter a description I would get back the ID value.

On can not use the standard because it blocked by PrestaShop.

I find this a situation:

$sql = "INSERT INTO `"._DB_PREFIX_."table`(`desc`) VALUES ('".$this->desc."')";
$restpo = Db::getInstance()->execute($sql);
var_dump($restpo);

But I have an answer only a boolean. Can you suggest something?

Upvotes: 2

Views: 6131

Answers (3)

Shadow
Shadow

Reputation: 34232

PrestaShop's DB class provides the last inserted id via

Db::getInstance()->Insert_ID(); 

method.

Upvotes: 2

sadlyblue
sadlyblue

Reputation: 2987

You can use the:

$id = (int)Db::getInstance()->Insert_ID();

For example, in the Cart class:

$last_id = (int)Db::getInstance()->Insert_ID();

I also recommend the use of the function insert, for example in the Carrier class:

$values = array();
foreach ($shops as $id_shop) {
      $values[] = array(
           'id_carrier' => (int)$this->id,
           'id_tax_rules_group' => (int)$id_tax_rules_group,
           'id_shop' => (int)$id_shop,
       );
}
$res = Db::getInstance()->insert('carrier_tax_rules_group_shop', $values);

Then use the Insert_ID to get the last one.

Upvotes: 9

TheDrot
TheDrot

Reputation: 4337

Use $id = Db::getInstance()->Insert_ID(); after executing your SQL.

Upvotes: 2

Related Questions