2017-07-01 36 views
1

我在保存數據時也嘗試保存值id。我可以用自動遞增選項來做到這一點,但有些原因,我不想將它用於數據庫。無法在mysql中保存增量值

即使我可以保存第一條記錄,但在此之後它會重複以前的ID。請幫我解決這個問題。非常感謝

控制器

public function ajax_add() 
{ 
    $this->_validate(); 
    $data = array(
     'VillageName'=> $this->input->post('VillageName'), 
     'VillageCode'=> $this->input->post('VillageCode'),        
     'VillageId_save'=> $this->input->post('VillageId_save'),         
     'VillageType'=> $this->input->post('VillageType'), 
     'BlockId'=> $this->input->post('BlockId'), 
     'CreatedBy' => $this->input->post('CreatedBy'), 
    ); 
    $insert = $this->village->save($data); 
    echo json_encode(array("status" => TRUE)); 
} 

public function get_lastvillageid() 
{ 
    $data = $this->village->getLastInserted(); 
    echo json_encode($data[0]['VillageId']); 
} 

查看

function save_vid() 
{ 
    var id = $('#VillageId_save').val(); 
    $.ajax({ 
      type:'POST', 
      dataType:'json', 
      url:'Village/get_lastvillageid', 
      data:{'id':id}, 
      success:function(response){  
       console.log("Data is : "+response); 
      console.log("Data is : "+ JSON.stringify(response)); 
       data = JSON.parse(response); 
       $("#VillageId_save").val(data); 
      } 
    }); 
} 

<input type="hidden" value="<?php 
    foreach ($getLastInserted as $row) {    
     echo $row['VillageId']+1; 
    }?>" name="VillageId_save" id ="VillageId_save"/> 

回答

0

使用PHP,

獲得最後插入使用MySQL和增量 「1」 的ID,然後將其插入。如果沒有記錄集默認「1」。

例如,

/* Set DB Connection. */ 
$select_last_id = "select max(id) as auto_inc from table name"; 
$res = mysqli_query($mysqli,$select_last_id); 
if(mysqli_num_rows($res)>0){ 
    $row = mysqli_fetch_array($res); 
    $new_increment_id = intval($row['auto_inc'])+1; 
} 
else{ 
    $new_increment_id = 1; 
} 
+0

我想通過ajax來做到這一點。否則會創建一個重複的ID。 –

+0

所以,你也把這個代碼放到你的ajax文件中。 –