2017-04-12 119 views
0

我有兩個表goals,goalscore如何通過sql中的外鍵關係將數據插入到兩個表中關聯php

goals table fields(GoalId,UserId,GoalName,StartDate,EndDate). 

GoalId主鍵(自動增量)

goalscore

(GoalScoreId, GoalId, GoalExpected,GoalAchieve, Score)

GoalScoreId(primarykey(auto increment)) GoalId(foreign Key from goals) 

現在我想從相同的形式將數據插入到兩個表。 第一張進球表和我想從中獲得的GoalId,並根據這個,需要將相同目標的相關數據插入到goalscore表中。

有時我正在使用for循環將多個數據插入到表中。所以最後的插入ID我不能拿。有沒有任何選擇。

請幫我找到解決方案。

代碼給出

public function AddNewGoal(){ 
$userid=$this->session->userdata['loggedin']['userId']; 

$Cdate=date('Y-m-d'); 
$Ldate=date('Y-m-d'); 
$date = $this->input->post('sdate'); 
//$freq = $this->input->post('frequency'); 
$freq= 1; 
$kpiId= $this->input->post('kpiname'); 
$goal = $this->input->post('Goal'); 
$goaltype = $this->input->post('goaltype'); 
$targetscore = $this->input->post('target'); 

$yearEnd = date('Y-m-d', strtotime('12/31')); 
//echo $yearEnd; exit(); 


$mnth= date('m', strtotime('-1 month')); 
$m = 12- $mnth; 
$q = 12-$mnth; 

If($freq==1){ 
    $i=1; 
    While ($i<= $m) 
    { 
     $query = $this->db->query('INSERT INTO goals 
     (UserId,KPITTemplateItemId,GoalTypeId,GoalStatusId,GoalDesc,StartDate,EndDate,CreatedOn,CreatedBy,LastModifiedOn,LastModifiedBy) 
     VALUES 
     (180,1,1,4,"goal","'.$date.'","'.$date.'","'.$date.'","'.$userid.'","'.$date.'","'.$userid.'")'); 
     $i++; 



    } 



} 
else if($freq==2){ 



} 
else if($freq==3){ 



} 
else if($freq==4){ 




} 
else if($freq==5){ 

    $query = $this->db->query('INSERT INTO goals 
     (UserId,KPITTemplateItemId,GoalTypeId,GoalStatusId,GoalDesc,StartDate,EndDate,CreatedOn,CreatedBy,LastModifiedOn,LastModifiedBy) 
     VALUES 
     (180,1,1,4,"goal","'.$date.'","'.$date.'","'.$date.'","'.$userid.'","'.$date.'","'.$userid.'")'); 


} 

if($this->db->affected_rows() > 0){ 
    return true; 
}else{ 
    return false; 
} 

}

+0

您是否嘗試先搜索答案?這是已經被多次回答的基本內容。請先搜索然後再試一次。 – Difster

+0

你的代碼在哪裏? 這些都是基本的東西,如果你嘗試在這裏分享 – anuraj

+0

我試過。但如果我插入單個數據,我可以使用最後插入的ID。但在我的情況下是根據目標頻率多次插入相同的數據 –

回答

0

你可以在MySQL中使用函數LAST_INSERTED_ID用於這一目的。

相關問題