获取最后插入 id return null

Get last insert id return null

我有带主键 ID 和自动递增的 db table 图像。正在使用 ajax > controller > model 添加新图像。

我的创建模型有方法 create

  public function create($data = array())
    {
        $this->db->insert($this->_table, $data);

        return $this->db->insert_id();
    }

  public function getLastInserted() {
        return $this->db->insert_id();
  }

并且在控制器中我创建了测试方法来检查最后插入的 ID 是什么:

public function lastID()
{
   var_dump($this->photo->getLastInserted());
}



// int(0)

但记录已成功插入数据库。可能是什么问题?

lastInsertid 仅当您在数据库连接变量上使用它时才有效,例如

dbconnection->lastInsertId()

来自官方文档:mysqli::$insert_id - Returns 上次查询中使用的自动生成的 id

确保您没有在 您的 create() 方法之后进行任何其他查询。

我建议将最后插入的 ID 放入 class 变量中,以避免将来出现此类问题:

private $lastInsertId = null;

public function create($data = array())
{
    $this->db->insert($this->_table, $data);
    $this->lastInsertId = $this->db->insert_id();

    return $this->lastInsertId;
}

public function getLastInserted() {
    return $this->lastInsertId;
}

您的创建函数 return 最后插入 ID。要查看您的最后一个插入 ID,只需在控制器函数中使用此代码

public function lastID()
 {
  var_dump($this->photo->create('table_name',$data));
 }

照片模型功能

function create($tableName, $data)
 {
    $this->db->insert($tableName, $post);
    return $this->db->insert_id();
 }