Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Monday, July 1, 2013

How to get last insert id in Magento query

Here is snippet for getting the ID of row after you have executed inserting the data into Magento table
01
02
03
04
05
06
07
08
09
10
11
12
13
function getLastInsertId($tableName, $primaryKey)
{
        //SELECT MAX(id) FROM table
        $db = Mage::getModel('core/resource')->getConnection('core_read');
        $result = $db->raw_fetchRow("SELECT MAX(`{$primaryKey}`) as LastID FROM `{$tableName}`");
        return $result['LastID'];
}
//Usage:
$setup = new Mage_Eav_Model_Entity_Setup('core_setup');
$optionTable = $setup->getTable('eav/attribute_option');
$lastInsertId = getLastInsertId($optionTable, 'option_id');

2 comments: