2017-04-12 48 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用于这一目的。

相关问题