如果主要,自动增量字段的列名称不是id,可以使用$ this-> db-> insert_id()函数

时间:2013-01-24 05:24:37

标签: php mysql codeigniter mysql-insert-id

我是Codeigniter的新手..

所以这是我的表:

request_id | login_name | login_password | reg_date |状态

如果主要自动增量列名称为$this->db->insert_id()而非request_id,是否可以使用id来获取最后插入的ID?

任何帮助将不胜感激..

3 个答案:

答案 0 :(得分:6)

是的,MySQLi中的insert_id并不关心列名,只是该列是AUTO_INCREMENT。它返回;

  

上一个查询更新的AUTO_INCREMENT字段的值。如果连接上没有先前的查询或查询未更新AUTO_INCREMENT值,则返回零。

答案 1 :(得分:1)

是的,你可以使用。

$this->db->insert_id()为您提供上次插入记录的ID,因此无需更改方法名称。

参考here

答案 2 :(得分:1)

是的使用$ this-> db-> insert_id()您可以获取表格中最后插入记录的ID。
像这样:

     <?php    
    class InsertRecord extends CI_Model {
    var $tablename = "test_table";
    var $primaryID = "request_id";

        function insertRecord(){
             $insertArr['login_name'] = $_POST['login_name'];
             $insertArr['login_password'] = $_POST['login_password'];
             $insertArr['reg_date'] = $_POST['reg_date'];       
             $insertArr['status'] = $_POST['status'];
             if ($this->db->insert($this->tablename, $insertArr)) {
                $lastInsertedID = $this->db->insert_id();
             }
        }
     }
    ?>

在$ lastInsertedID变量中,您将获得最后插入记录的ID。

希望这会对你有所帮助...... :)