这是我的数据库配置:-
$db['default'] = array(
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'test_db',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => TRUE,
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
我使用这个插入用户并输出die();
上的最后一个id
$this->db->insert("user",$data);
$lastid=$this->db->insert_id();
die($lastid);`
输出0
但是当我使用:-
$query = $this->db->query('SELECT LAST_INSERT_ID()');
$row = $query->row_array();
$lastid= $row['LAST_INSERT_ID()'];
die($lastid);
输出最后插入的id…
我在user_id
上有一个auto_increment
为什么$this->db->insert_id()
不能工作?
根据我给你的链接(在评论中):-
1。从第一个链接($this->db->insert_id();在codeigniter中每次返回0)您可能没有主键自动递增列。所以你可以使用:-
$this->db->affected_rows()
(但这不会给你最后插入的id,它会告诉你有多少行由于插入查询而受到影响)
2。从第二个链接(https://kedyr.wordpress.com/2012/10/03/codeigniter-insert_id/)完全相同的解决方案给出了你已经尝试过的第二次尝试(这是为你工作),但没有解释为什么会发生这种行为。
3。基于:- http://forum.codeigniter.com/thread-61881.html
mysql在提交事务(预期行为)时重置插入id。当它没有事务时,我认为由于错误,不同PHP版本的行为不同。通过调用trans_begin(),然后是insert(),然后是insert_id(),最后是commit(),尝试将其包装在事务中。
但我认为这是一个非常高端的概念(即使我不知道如何执行这个,所以没有注释)。
4.从这个链接:- https://github.com/bcit-ci/CodeIgniter/issues/591它又在说:-
。如果没有auto_increment列,它将返回0
b。没有mysqli连接/链接id将返回false(在php中实际上是0)。
最后再试一次:-
$this->db->insert("user",$data);
$lastid=$this->db->insert_id();
echo $lastid;die;
我检查过了,它工作得很好。请这样试一试
public function addNewAdmin($data) {
$result = $this->db->insert("admins", $data);
$lastid=$this->db->insert_id();
echo $lastid;exit;
}
$this->db->insert_id()返回插入的最后一行的id,确保您已将id列设置为自动递增的主键。使用;
$this->db->insert('table',$array(''=>,));
$id=$this->db->insert_id();`enter code here`
return $id;
我认为id没有被返回,因为您的自动增量值不仅仅是普通id,而是user_id..这是因为我尝试了
$this->db->insert("user",$data);
$lastid=$this->db->insert_id();
die($lastid);
有一个表的ID,它工作,但当我尝试它与item_id表在同一个项目,没有工作