问题描述
我正在将Kohana 3框架与Mysql存储过程一起使用.如何获取最后插入的记录的ID?这是代码:
I'm using Kohana 3 framework with Mysql stored procedures. How can I get id of the last inserted record?Here's the code:
class Model_MyModel extends Kohana_Model
{
public function insertNew($param1, $param2)
{
$result = $this->_db->query(Database::INSERT, 'CALL insertNew('.$param1.', '.$param2.', false)';
return $result;
}
...
...
}
文档说,执行插入查询时,query()方法返回一个带有最后一个插入ID和受影响的行号的数组.当我打电话时:print_r($ result)我越来越:大批( [0] => 0 [1] => 1)尽管我在数据库中有很多记录,但是insert_id键为0.我在做什么错了?
Documentation says, the query() method returns an array with the last insert id and affected rows number, when executing an insert query. When I call: print_r($result)I'm getting:Array( [0] => 0 [1] => 1)The insert_id key is 0, though I'm having many records in the db.What I'm doing wrong?
推荐答案
我认为您在使用过程插入后必须使用SQL的LAST_INSERT_ID()
:
I think you'll have to use SQL's LAST_INSERT_ID()
after inserting using a procedure:
SELECT LAST_INSERT_ID() as last_insert_id FROM table_name
(在您的过程中,只需在最后定义此查询即可).
( in your procedure just define this query in the end ).
在这种情况下,问题在于Kohana会自动返回mysql_insert_id和mysql_affected_rows作为Database :: INSERT的结果,因此您需要以SELECT查询的形式调用该过程并获取它(Database :: SELECT).
The problem in this case is that Kohana automatically returns mysql_insert_id and mysql_affected_rows as result for Database::INSERT, so you'll need to call the procedure as a SELECT query and fetch it (Database::SELECT).
这篇关于insert_id在Kohana 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!