How to retrieve inserted ID after using add() on an Object?
Asked Answered
G

2

5

I am trying to create a script that automatically imports a XML file, I got this working, but for a reason I need to get the ID from a category I am adding, this category ID is auto increment, so there is no way I could get this out of the existing data.

So my code looks like this:

        $category = new Category;
        $category->active = 1;
        $category->id_parent = 3;
        $category->name[1] = $product->category_name;;
        $category->link_rewrite[1] = Tools::link_rewrite($product_xml->category_name);
        echo "<br />name of new category = $product->category_name <br /> <br />";
        $category->add();
        $category->id = Db::getInstance()->Insert_ID();

I have read somewhere here on stackoverflow that

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

Should do the trick. Unfortunately, this returns always zero. Can someone see what I did wrong?

Edit: I am using prestashop version 1.6

Edit: Answer: You don't need "Db::getInstance()->Insert_ID();" after $object->add() there is already an ID generated, the only thing you have to do is: echo $object->id; and you'll see your ID.

Best regards,

Evert Arends

Gil answered 14/1, 2016 at 9:27 Comment(2)
Witch Prestashop version are you using ?Discordancy
I am using version 1.6Gil
D
8

Prestashop already did this command in classes/ObjectModel.php method add()

// Get object id in database
$this->id = Db::getInstance()->Insert_ID();

When you use add() on an object this object automatically get its new id from database. So $category->id should already contain its new ID.

$category = new Category;
$category->active = 1;
$category->id_parent = 3;
$category->name[1] = $product->category_name;;
$category->link_rewrite[1] = Tools::link_rewrite($product_xml->category_name);
echo "<br />name of new category = $product->category_name <br /> <br />";
$category->add(); // Add will add the category to database and update category with its new id automatically
echo "category id = ".$category->id; // will show the category id.
Discordancy answered 14/1, 2016 at 9:38 Comment(3)
But why does it return 0? I am sorry if I get your answer wrong, not a native speaker.Gil
Because Prestashop already retrieved the last ID via Insert_ID. This method can be used only once per add.Discordancy
aaand now I get it, thanks for your help, I will edit my question with this information. Thanks!Gil
B
-1
Last Inserted Id:

      echo $category->id;
Bellwether answered 14/10, 2016 at 8:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.