根据user_name抓取最后一个id - codeigniter

时间:2013-05-28 17:04:34

标签: php sql codeigniter

我正在开发一个包含一篇主要文章的项目,您可以附加许多不同的文章。因此,在提交时,我将文章分成两个不同的部分,因为我需要将它们提交到两个不同的表中。

提交第一部分后,我正在尝试根据其user_name获取最后提交的ID,以便我可以附上文章的其余部分。如果这是有道理的。

我尝试了几种不同的东西,但似乎没有什么可以夺回那个身份。

首先我尝试了insert_id()meathod,但返回0

public function pullLastStoryId($author){
    $this->db->where('author', $author);
    $this->db->insert_id();
    $story = $this->db->get('story_tbl');
    return $story->result();    
} 

那么我也试着抓住

public function pullLastStoryId($author){
    $story = $this->db->query('SELECT LAST_INSERT_ID() INTO story_tbl;')
    return $story->result();    
}   

任何想法

3 个答案:

答案 0 :(得分:0)

我不清楚这个问题。你在寻找这样的东西吗?

public function pullLastStoryId(){
    $story = $this->db->query('SELECT id from tablename where id = LAST_INSERT_ID()')
    return $story->result();    
}   

OR

public function pullLastStoryId(){
    $id = $this->db->insert_id();
    $this->db->where('id',$id);
    $story = $this->db->get('story_tbl');
    return $story->result();    
} 

答案 1 :(得分:0)

我的猜测是你在谈论两个表之间的外键关系。一种方法是这样的:

$this->db->insert('author',$vals);
$id = $this->db->insert_id();
// do something with ID.

据我所知,你可能会做这样的事情:

$story_row = $this->db->get_where('story_tbl',array('id' => $id));

您不必担心不同的user_name属性,因为这将是最后创建的ID。但是,如果你真的想要回到那一行,你可以这样做:

$author_row = $this->db->get_where('author',array('author_id' => $id));

如果您需要在其他地方使用此ID(例如,提交另一个表单后),您可以使用hidden表单输入或(这样更安全一点),您可以将该ID存储在会话。

答案 2 :(得分:-1)

如果你想获得姓氏,你的方式是错误的。 $ this-> db-> insert_id()或等等用于活动查询。试试这个:SELECT id FROM table ORDER BY id DESC LIMIT 1