zend framework insert() and LAST_INSERT_ID() screw up
so I tried to use Zend_Db_Adapter_Pdo_Mysql's insert() method....
and then after that I issued the SELECT LAST_INSERT_ID();
command....
but then for some reason, that command always return 0 rather than the actual inserted ID...
when I tried to use normal INSERT query, and then get the last insert id, it works just fine so I guess it's some zend framework screw up...
does anybody know how to get around this?
the insert() method only returns 1 if it succeeds rather than the id, so the solu开发者_如何转开发tion for this: last insert id with zend db table abstract doesn't seem to work
Your question is very unclear. Nevertheless, I think that at least a part of a problem you have is that you are confusing insert method from Zend_Db_Adapter_Abstract
(or Zend_Db_Adapter_Pdo_Mysql
) with the one from Zend_Db_Table_Abstract
. Both these classes have methods that are called insert
, but they work differently.
insert
methods from Zend_Db_Adapter_Abstract
returns the "The number of affected rows", while insert
from Zend_Db_Table_Abstract
returns "The primary key of the row inserted".
The link that you provided is using insert from Zend_Db_Table_Abstract
. However, it seems that you are using insert from `Zend_Db_Table_Abstract
. For this reason you are always getting 1 in return.
Zend_Db_Adaptor Documentation explains
Some RDBMS brands support auto-incrementing primary keys. A table defined this way generates a primary key value automatically during an INSERT of a new row. The return value of the insert() method is not the last inserted ID, because the table might not have an auto-incremented column. Instead, the return value is the number of rows affected (usually 1).
If your table is defined with an auto-incrementing primary key, you can call the lastInsertId() method after the insert. This method returns the last value generated in the scope of the current database connection.
So ...
$id = $db->lastInsertId();
Should work
In ZF2 you could use :
$id = $this->lastInsertValue;
In ZF3 & Zend Expressive, this is the only way to do it:
$this->dbAdapter->getDriver()->getLastGeneratedValue();
精彩评论