Kohana 3: Getting the insert_id after an INSERT query

Since the database library in Kohana 3 is so much different than in Kohana 2, to get the last insert id of a row, use the following code instead:


$insertTable = DB::query(Database::INSERT,
		"INSERT INTO table (x, y, z) " .
		"VALUES(@x, @y, @z)"
);
$insertTable->param('@x', $x);
$insertTable->param('@y', $y);
$insertTable->param('@z', $z);
$insertTableResult = $insertTable->execute();

$insert_id = $insertTableResult[0];

I’m not too sure what the other ways of doing it is, but this is the only way I found after looking at the code.

No thanks to kohana 3’s non-existent documentation.


Addendum: As Sicabol suggested, the code above can be simplified by using list() instead of manually creating and using a separate array. That is:


$insertTable = DB::query(Database::INSERT,
		"INSERT INTO table (x, y, z) " .
		"VALUES(@x, @y, @z)"
);
$insertTable->param('@x', $x);
$insertTable->param('@y', $y);
$insertTable->param('@z', $z);
list($insert_id, $total_rows_affected) = $insertTable->execute();

One thought on “Kohana 3: Getting the insert_id after an INSERT query

  1. You could try :

    list($insert_id, $total_rows_affected) = DB::insert(‘table_name’, array(‘x’, ‘y’, ‘z’))
    ->values(array($x, $y, $z))
    ->execute();

Leave a Reply

Your email address will not be published.