Php 如何将表单中的数据插入数据库,并获取最后插入的ID/create uniqueID作为用户在CI中的会话

Php 如何将表单中的数据插入数据库,并获取最后插入的ID/create uniqueID作为用户在CI中的会话,php,codeigniter-3,codeigniter-2,Php,Codeigniter 3,Codeigniter 2,我正在尝试向数据库提交表单,并希望创建会话。可以使用的会话可以是最后插入的ID,也可以创建唯一ID作为会话。我所面临的问题是,每当我试图刷新页面时,我的sessionID就会不断增加,因为新记录被插入到数据库中 视图:Welcome_Message.php 提交表单时,它会在数据库中插入数据,并获取数据,将计算出的估计报价返回给用户。如果用户刷新页面,我希望停止在数据库中插入数据,或者使用会话来显示 提前感谢您的时间 首先在模型检查中,如果是新记录,则直接插入,否则返回旧id。 类似于此: $t

我正在尝试向数据库提交表单,并希望创建会话。可以使用的会话可以是最后插入的ID,也可以创建唯一ID作为会话。我所面临的问题是,每当我试图刷新页面时,我的sessionID就会不断增加,因为新记录被插入到数据库中

视图:Welcome_Message.php

提交表单时,它会在数据库中插入数据,并获取数据,将计算出的估计报价返回给用户。如果用户刷新页面,我希望停止在数据库中插入数据,或者使用会话来显示


提前感谢您的时间

首先在模型检查中,如果是新记录,则直接插入,否则返回旧id。 类似于此:

$temp = $data;
unset($temp['SessionID']);
$this->db->where($temp);
$query = $this->db->get('Quote_Form');
if ($query->num_rows() > 0) {
    $result = $query->result();
    return $idOfInsertedData = $result->id;
}
$this->db->insert('Quote_Form', $data);
return $idOfInsertedData = $this->db->insert_id();

实际上,PHP中有一个预定义的函数,名为last insert id。它可以在PDO和mysqli中使用。在php模型中:

 function insertToQuoteForm($data) {
      if($this->db->insert('Quote_Form', $data)){ //check if successful
          return $this->db->lastInsertId(); //return the ID of the last insert
      }
 }
在quote.php中,您需要添加以下内容:

 $sID = $this->PostModel->insertToQuoteForm($data);
 $_SESSION['lastInserted'] = $sID;

谢谢@JJ Laboja,我能够获取最后一个插入的ID,并尝试将此ID作为flashdata。但当我刷新页面时,它再次生成新的ID,我丢失了最后一个注册为flashdata的ID。我也试过userdata和同样的问题。@SarahMalik基于你的代码,每次你在表单中插入数据时,它都会生成新的ID。从技术上讲,这不是问题。如果您发现它是一个问题,那么您必须以应该的方式更改程序的逻辑。我很高兴我帮了点忙。
$temp = $data;
unset($temp['SessionID']);
$this->db->where($temp);
$query = $this->db->get('Quote_Form');
if ($query->num_rows() > 0) {
    $result = $query->result();
    return $idOfInsertedData = $result->id;
}
$this->db->insert('Quote_Form', $data);
return $idOfInsertedData = $this->db->insert_id();
 function insertToQuoteForm($data) {
      if($this->db->insert('Quote_Form', $data)){ //check if successful
          return $this->db->lastInsertId(); //return the ID of the last insert
      }
 }
 $sID = $this->PostModel->insertToQuoteForm($data);
 $_SESSION['lastInserted'] = $sID;