获取上次更新记录的id


Get the id of the last updated record

我可以使用codeigniter中的$this->db->insert_id();获得最后插入的id,有什么方法可以获得最后更新的记录的id吗?我用相同的$this->db->insert_id();尝试了它,但它不起作用(返回0)。

Codeigniter不支持这一点。我不得不这么做:

$updated_id = 0;
// get the record that you want to update
$this->db->where(array('vrnoa'=>$data['vrnoa'], 'etype' => 'sale'));
$query = $this->db->get('StockMain');
// getting the Id
$result = $query->result_array();
$updated_id = $result[0]['stid'];
// updating the record
$this->db->where(array('vrnoa'=>$data['vrnoa'], 'etype' => 'sale'));
$this->db->update('StockMain',$data);
$this->db->insert_id();  

这将只提供插入的id。为了获得更新的行id,您可以添加一列作为lastmodified(timestamp),并在每次运行更新查询时使用当前时间戳更新此列。更新查询后只需运行以下命令:

$query = $this->db->query('SELECT id FROM StockMain ORDER BY lastmodified DESC LIMIT 1');  
$result = $query->result_array();  

您将在结果集中获得id。

以下是如何实现最短

$where  =   array('vrnoa'=>$data['vrnoa'], 'etype' => 'sale');

//更新记录

$this->db->where($where);
$this->db->update('StockMain',$data);

//获取记录

$this->db->where($where);
return $this->db->get('StockMain')->row()->stid;

返回您在where子句中用于更新的id

function Update($data,$id){
        $this->db->where('id', $id);
        $this->db->update('update_tbl',$data);
        return $id; 
    }

使用代码点火器和MY_MODEL作为扩展版本。这是我如何重获新生的瓶颈之一。

  function update_by($where = array(),$data=array())
  {
        $this->db->where($where);
        $query = $this->db->update($this->_table,$data);
        return $this->db->get($this->_table)->row()->id; //id must be exactly the name of your table primary key
  }

调用这个Updates并获取更新的id。我想运行两次查询有点过头了,但以上所有操作都是如此。

你怎么打电话?

 $where = array('ABC_id'=>5,'DEF_ID'=>6);
 $data =  array('status'=>'ACCEPT','seen_status' =>'SEEN');
 $updated_id= $this->friends->update_by($where,$data);

这样尝试:

  //update
    public function update($table, $where, $data)
    {
        // get the record that you want to update
        $this->db->where($where);
        $query = $this->db->get($table);
        // getting the Id
        $row = array_values($query->row_array());
        $updated_id = $row[0];
        // updating the record
        $updated_status = $this->db->update($table, $data, $where);
        if($updated_status):
            return $updated_id;
        else:
            return false;
        endif;
    }