如何在sql php中将数据插入到外键关系相关的两个表中

时间:2017-04-12 08:04:50

标签: php mysql

我有两张表goalsgoalscore

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;
}

}

1 个答案:

答案 0 :(得分:0)

您可以在mysql中使用函数last_inserted_id来实现此目的。