如何获取最后插入的id,然后将其分配给全局变量


How to get last inserted id, then assign it to a global variable

我想获得最后插入的id,然后将其分配给一个全局变量,以便稍后使用。

我使用callback_after_insert如下:

$crud->callback_after_insert(array($this, '_callback_get_lastInsertID'));
function _callback_get_lastInsertID($post_array,$primary_key) {
   $this->lastInsertedId = $primary_key;
}

然后,当使用$this->lastInsertedId获取其值时,但我找不到任何值​​存储。

function featured_ad_offer() { 
    echo $this->lastInsertedId; 
    @$data['content'] .= $this->load->view('featured_ad_offer', '', true); 
    $this->load->view('index', $data); 
}

有一条错误消息说Undefined property: Content::$lastInsertedId

现在,如何做到这一点?

请在"声明"类本身(即)之后立即尝试在类中声明变量(假设两个函数都在同一类中)

class Blog extends CI_Controller {
    private $lastInsertedId = NULL;
    public function fcn1() {$this->lastInsertedId = 3.14;}
    public function fcn2() {var_dump($this->lastIndertedId);}
}

如果你真的想把它用作global variable,你需要在CI_Controller中声明它,或者最好在/core/Public_Controller中创建一个扩展CI_Controller的文件,并让所有控制器不是由CI_Controller扩展,而是由Public_Controller扩展,因此你可以很容易地声明"全局"变量。

有关扩展的更多信息,请使用Phil.的本教程

如果你有问题,这里有一个用户指南链接。

还有另一个选项(不推荐!)配置类

$this->config->set_item('item_name', 'item_value'); //setting a config value
$this->config->item('item name'); //accesing config value

也许您可以使用它来获取最后插入的id

$this->db->insert_id();

将其存储在会话中

$this->load->library('session');
$this>session->set_userdata('last_inserted_id');

并在其他地方使用此会话变量

$last_inserted_id = $this->session->userdata('last_inserted_id');

希望得到帮助:D

您需要的解决方案可以通过Codeigniter会话轻松解决。例如,你可以做的是:

$crud->callback_after_insert(array($this, '_callback_get_lastInsertID'));
function _callback_get_lastInsertID($post_array,$primary_key) {
   $this->session->set_userdata('last_insert_id', $primary_key);
}

请确保先加载会话类。最好的方法是在自动加载时实际拥有会话库。

现在,要再次实际调用last_insert_id,只需调用:即可

echo $this->session->userdata('last_insert_id');

所以在你的例子中,你可以简单地做:

function featured_ad_offer() { 
    echo $this->session->userdata('last_insert_id'); 
    @$data['content'] .= $this->load->view('featured_ad_offer', '', true); 
    $this->load->view('index', $data); 

}