Wednesday 14 August 2013

Magento - Get Last Insert Id

- To get last inserted in magento there is two ways based on the insert method

First:

$connection    = Mage::getSingleton(’core/resource’)->getConnection(’core_write’);
$sql         = ”INSERT INTO `table` SET field1 = ?, field2 = ?, …”;
$connection->query($sql, array($field1_value, $field2_value, …));
$lastInsertId = $connection->lastInsertId();
echo $lastInsertId;


Second:

  $customAddress = Mage::getModel('customer/address');

         $customAddress->setData($_custom_address)
            ->setCustomerId($customer->getId())
            ->setIsDefaultBilling('0')
            ->setIsDefaultShipping('1')
            ->setSaveInAddressBook('1');

         try {
           $customAddress->save(); 
echo $customAddress->getId();

2 comments: