Magento – get generated Id from custom write connection

databasemagento-1sql

in my plugin I use an additional table. That table has an id, which is set to AUTO_INCREMENT.
When I insert something in there, I do something like:

$resource = Mage::getSingleton('core/resource');
$writeConnection = $resource->getConnection('core_write');
$query = 'INSERT INTO test (column1, column2) VALUES (3, 4)';
$writeConnection->query($query);

In this case the table test has also an id.
Is there a way I could get this id after I inserted it?

Best Answer

You can get it like this:

$writeConnection->lastInsertId();

But you are doing it wrong.
You should have a model and a resource model that maps on your table and you should use the ORM to persist data.
Have something like this:

$model = Mage::getModel('[module]/test');
$model->setData(array('column1' => 3, 'column2' => 4 ));
$model->save();
$id = $model->getId();