Search code examples
mysqlzend-frameworkzend-dbzend-db-table

Getting the last User ID in Zend Framework


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?


Solution

  • The answer was:

    $sql = 'SELECT max(id) FROM user';  
            $query = $this->getAdapter()->query($sql);
            $result = $query->fetchAll();
            return $result[0]['max(id)'];