我有两个表目标
,goalscore
。
goals table fields(GoalId,UserId,GoalName,StartDate,EndDate).
GoalId
是主键(自动增量)。
在goalscore
表中
(GoalScoreId、GoalId、GoalExpected、GoalAchieve、分数)
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;
}
}
最佳答案
您可以在 mysql 中使用函数last_inserted_id来实现此目的。
关于php - 如何在sql php中通过外键关系将数据插入到两个表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363749/