2013-03-03 49 views
0

我有這個功能,它下面笨batch_update,插入確認

function save($owner,$data){ 
///$owner='00002';$data=[['type1','value1'],['type','value2']]; 
///check if this $data is already in database, if +ve and != then update else insert 
     $sel='';$rs=[];$ins=FALSE;$up=FALSE;$end=[]; 

     $this->db->select('id,type,value')->where('owner',$owner) 

     //building WHERE statment 
     foreach(array_keys($data)as $k) 
      $sel.="type='$k' OR "; 

     $this->db->where("(".trim($sel,' OR ').")"); 

     $r=$this->db->get('settings'); 

     if($r->num_rows() > 0)//building reference array 
      foreach($r->result() as $r)$rs[$r->type]=$r; 

     foreach($data as $t=>$v) 
     { 
      if(isset($rs[$t])){//case input already in db-->update 
       if(!$v || $v!=$rs[$t]->value)$up[]=['id'=>$rs[$t]->id,'value'=>$v,'archived'=>0]; 
      }else{//case not-->insert 
       if($v)$ins[]=['type'=>$t,'value'=>$v,'owner'=>$owner]; 
      } 
     } 

     $this->db->insert_batch('settings',$ins); 
     $this->db->update_batch('settings',$up,'id'); 
    } 

現在,我怎麼確認insert_batch和update_patch都工作和如何返回有多少個字段,其中更新.. 我試着使用DB-> affected_rows()但由於即時通訊使用2個語句,其返回值不準確。

有什麼想法?

回答

1

如何爲它創建一個變量?

private $inserted_num_rows; 
private $updated_num_rows; 

然後存儲到受影響的行

$this->db->insert_batch('settings',$ins); 
$this->inserted_num_rows = $this->db->affected_rows(); 

$this->db->update_batch('settings',$up,'id'); 
$this->updated_num_rows = $this->db->affected_rows(); 

然後只需創建一個getter返回數據

function get_inserted_num_rows() 
{ 
    return $this->inserted_num_rows; 
} 

function get_updated_num_rows() 
{ 
    return $this->updated_num_rows; 
}