Getting the last User ID in Zend Framework
Posted
by
Ryan Murphy
on Stack Overflow
See other posts from Stack Overflow
or by Ryan Murphy
Published on 2012-05-04T14:38:45Z
Indexed on
2012/06/16
21:16 UTC
Read the original article
Hit count: 225
Using MySQL query browser, I manually made a table called users
and input some date in the fields. I set the primary key
to id
and set it to auto increment
. There are 3 rows
, the highest id
is 3
.
I then made the following class
in the method
directory to call upon the data in the table etc.
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
protected $_name = 'user';
public function getLatestUserId()
{
$id = $this->getAdapter()->lastInsertId();
return $id;
}
}
In the controller
I do the following which gets the value generated by the method
and lets the view
access it:
$usersDbModel = new Application_Model_DbTable_User();
$lastUserId = $usersDbModel->getLatestUserId();
$this->view->lastUserId = $lastUserId;
In the view I then echo it to display it to the user:
echo $this->lastUserId;
However, even though my last id
in the users
table is 3. It displays 0.
I have also tried:
public function getLatestUserId()
{
$sql = 'SELECT max(id) FROM user';
$query = $this->query($sql);
$result = $query->fetchAll();
return $result;
}
But this just throws out a server error.
What have I done wrong?
Am I missing something?
Is there another way of doing this?
© Stack Overflow or respective owner