【问题标题】:Getting the last User ID in Zend Framework在 Zend Framework 中获取最后一个用户 ID
【发布时间】:2012-05-04 14:38:45
【问题描述】:

使用 MySQL 查询浏览器,我手动创建了一个名为 users 的表,并在字段中输入了一些日期。我将primary key 设置为id 并将其设置为auto increment。有3 rows,最高的id3

然后我在method 目录中创建了以下class 来调用表中的数据等。

class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
    {
        protected $_name = 'user';  

        public function getLatestUserId()
        {
            $id = $this->getAdapter()->lastInsertId();
            return $id;
        }   
    }

controller 中,我执行以下操作,获取method 生成的值并让view 访问它:

   $usersDbModel = new Application_Model_DbTable_User();
    $lastUserId = $usersDbModel->getLatestUserId();     
    $this->view->lastUserId = $lastUserId; 

然后我在视图中回显它以显示给用户:

echo $this->lastUserId;

但是,即使我在 users 表中的最后一个 id 是 3。它显示为 0。

我也试过了:

 public function getLatestUserId()
    {    
        $sql = 'SELECT max(id) FROM user';  
        $query = $this->query($sql);
        $result = $query->fetchAll();
        return $result;
    }   

但这只会抛出服务器错误。

我做错了什么?
我错过了什么吗?
还有其他方法吗?

【问题讨论】:

    标签: mysql zend-framework zend-db zend-db-table


    【解决方案1】:

    答案是:

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

    【讨论】:

    • 只考虑在多个客户端向数据库插入记录的环境中使用这是不安全的,另一个客户端可能会在您的客户端应用程序执行的插入和您的查询之间的瞬间插入另一行对于 MAX(id),因此返回的 max(id) 不能识别插入的最后一行
    【解决方案2】:

    如果您查询“SELECT id FROM USERS SORT BY id DESC LIMIT 0,1”

    除了最新用户的 id,你什么也得不到,不是吗?

    【讨论】:

    • 你的表是user还是users
    【解决方案3】:

    如果你使用像这样的选择语句

    SELECT max(id) FROM USERS;
    

    如果您还没有尝试在控制器中使用函数,请尝试这样的操作。

    class IndexController extends Zend_Controller_Action {
    
         public function init() {
    
        }
    
        public function indexAction() {
    
        }
    
        public function getLatestUserId()
        {
             $bootstrap = $this->getInvokeArg('bootstrap');
             $resource = $bootstrap->getPluginResource('db');
             $db = $resource->getDbAdapter();
    
             $sqlrequest = "select max(id) as Idmax from user";
             $rows = $db->fetchAll($sqlrequest);     
    
             foreach ($rows as $row)
                 echo $maxId = $row['Idmax'];       
    
             return $maxId;
        }
    }
    

    你的引导文件看起来像

     class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
     {
    
         protected function _initConfig()
        {
            $config = new Zend_Config($this->getOptions());
            Zend_Registry::set('config', $config);
            return $config;
        }
    }
    

    希望类似的方法有效,希望对您有所帮助

    【讨论】:

    • 我不确定把它放在那个类中是不是最好的解决方案,你是否尝试过从控制器发出请求?
    • 看来你的解决方案比我的好很多哈哈哈,很高兴解决了。
    【解决方案4】:

    问题是 Mysql 并不真正支持lastInsertId(),它在某些情况下会返回自动递增主键的最后一个 id。
    这里介绍了几种解决方案,大多数会返回主键的最后一个 id,这可能是您真正需要的,也可能不是。

    此方法也将使用 select() 对象执行相同的操作。

    public function getlastInsertId(){
            $select = $this->select();
            $select->from($this->_name, "id");
            $select->order('id DESC');
            $select->limit(0, 1);
            $result = $this->fetchAll($select)->current();
    
            return $result->id;
        }
    

    我认为,如果您真正追求的是您插入的最后一个 id,那么随着时间的推移,您可能会发现这些方法不可靠。随着时间的推移,随着记录的添加和删除,数据库可能会或可能不会填补空缺的 ID,具体取决于您当前使用的数据库以及该数据库的设置方式。
    在大多数情况下,我们需要在插入后很快插入的最后一个项目的 id,通常是为了更新视图脚本。在这种情况下,我通常只是将整个行对象作为返回的一部分。

    这是我的意思的一个例子:

    /**this method will save or update a record depending on data present in the array*/
    public function saveUser(array $data) {
            /**cast data array as std object for convience*/
            $dataObject = (object) $data;
            /**if id exists as array and has a non null value*/
            if (array_key_exists('id', $data) && isset($data['id'])) {
                /**find row if updating*/
                $row = $this->find($dataObject->id)->current();
            } else {
                /**create new row*/
                $row = $this->createRow();
            }
    
            $row->first_name = $dataObject->first_name;
            $row->last_name = $dataObject->last_name;
            $row->email = $dataObject->email;
            /**save or update row*/
            $row->save();
            /**return the $row you just built or you can return $result = $row->save(); and get*/
            /** just the primary key. Save() will throw an exception if table is marked read only*/
            return $row;
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 2011-04-30
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      • 1970-01-01
      • 2011-05-19
      相关资源
      最近更新 更多