首页 > 解决方案 > 将last_inserted id从一个函数传递给codeigniter中同一类中的另一个函数

问题描述

我想将我的变量 $lastid 传递给同一类中的另一个函数。我该怎么做??..我尝试了一些东西,但它不起作用?

class ProductmModel extends CI_Model
{

  var $PRODUCTNAME='';
  var $DESCRIPTION='';
  var $CATEGORY='';
  var $SUBCAT='';
  var $IMAGE='';


public function addproductm()
{
$this->load->database();
$data = array(
"p_name" => $this->PRODUCTNAME,
"p_des" => $this->DESCRIPTION,
"cat" => $this->CATEGORY,
"subcat" => $this->SUBCAT

);
$this->db->insert('product_multi', $data);
$lastid = $this->db->insert_id();

}

这是下一个功能

public function addimage()
{
$last= $this->addproductm();
$this->load->database();

$data = array(
"pid" => $lastid,
"images" => $this->IMAGE

);
$this->db->insert('image', $data);
}
}

标签: phpfunctioncodeigniterclassmysqli

解决方案


首先,确保您的表中有一个自动递增的 id

二、$this->db->insert_id()插入后返回from模型

public function addproductm()
{
    $this->load->database();
    $data = array(
       "p_name" => $this->PRODUCTNAME,
       "p_des" => $this->DESCRIPTION,
       "cat" => $this->CATEGORY,
       "subcat" => $this->SUBCAT
    );
    $this->db->insert('product_multi', $data);
    return $this->db->insert_id();
}

在这里,您在模型中获得了最后插入的 id,例如$last_id = $this->db->insert('image', $data)

传递$last_idto 函数

public function addimage()
{
   $last= $this->addproductm();
   $this->load->database();

   $data = array(
      "pid" => $lastid,
      "images" => $this->IMAGE
   );
   $last_id = $this->db->insert('image', $data);
   $this->function_name($last_id);
}

推荐阅读