1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

How to get last insert id after call $dw->save();

Discussion in 'General PHP and MySQL Discussions' started by timothy259856, Oct 6, 2014.

  1. timothy259856

    timothy259856 Active Member

    Hello guys!

    When I execute an insert item to my table use $dw->save(); how can I get the id which created after call save()?

    I know that Zend support the $db->lastInsertId() but where to do this? Do I need do anything in the DataWriter?

    Thank you!
     
  2. Chris D

    Chris D XenForo Developer Staff Member

    PHP:
    $dw->get('whatever_your_id_field_is_called');
     
    SneakyDave and timothy259856 like this.
  3. timothy259856

    timothy259856 Active Member

    Understood! Thanks for your support :)
     
  4. timothy259856

    timothy259856 Active Member

    Sorry but look like it cannot get the key of table, I have defined the key with name is "id" auto increasment but after call $dw->save(), it's return null when get the "id".
     
  5. Chris D

    Chris D XenForo Developer Staff Member

    In that case, try:

    PHP:
    $dw->save();
    $record $dw->getMergedData();
    $id $record['id'];
     
    timothy259856 likes this.
  6. timothy259856

    timothy259856 Active Member

    Error: Undefined index: id
     
  7. Chris D

    Chris D XenForo Developer Staff Member

    What is the name of your auto increment field in the database?
     
  8. timothy259856

    timothy259856 Active Member

    "id" , I try to var_dump the $recod and saw that it's contain all field except the "id".
     
  9. Chris D

    Chris D XenForo Developer Staff Member

    Are you sure the $dw->save(); actually worked without errors? You're not forcing the errors to be silent? Can you see the data in the database at that point?

    This approach is used throughout XenForo to get the data that's just been saved to the database.
     
  10. timothy259856

    timothy259856 Active Member

    Yes, I do the check, I saw the data was insert in database. I can get others field but not for the key.
     
  11. Chris D

    Chris D XenForo Developer Staff Member

    Is your id field marked as "autoIncrement" in the _getFields function in your datawriter?
     
    AndyB and timothy259856 like this.
  12. timothy259856

    timothy259856 Active Member

    Oops! Missing that mark, it's work now. Thanks Chris :)
     
    Chris D likes this.

Share This Page