简体   繁体   中英

How to insert data into two table related by foreign key relation in sql php

I have two table goals , goalscore .

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

GoalId is the primary key(auto increment) .

In goalscore table

(GoalScoreId, GoalId, GoalExpected,GoalAchieve, Score)

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

Now I want to insert data from the same form to both the table. First goals table and from that table I want to get GoalId and according to that, need to insert related data of the same goal to goalscore table.

Sometimes am using for loop to insert multiple data to the table. So last insert id I can't take. Is there any option.

Please help me to find the solution.

code is given

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

}

为此,您可以在mysql中使用函数last_inserted_id。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM