0

Not sure that this is even possible. I am inserting values into two tables at the same time using multi_query. That works fine. One of the tables has an auto increment column and I need to take the last auto incremented number and insert it into the second table so like this: insert into table 1 then take the last inserted number from column X and insert it along with other data into table 2. I have played around with using SELECT LAST and INSERT INTO but so far its just doing my head in. The insert statements looks like this:

$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate)     VALUES ('$riskclient2', '$facility2', '$riskdate2');";

$sql .="SELECT     LAST(riskId) FROM tbleClients;";$sql .="INSERT INTO tblRiskRegister (riskId)     SELECT riskId FROM tbleClients ;";

$sql .= "INSERT INTO tblRiskRegister     (riskAudDate, riskClientId,       riskSessionId, RiskNewId) VALUES     ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";

Individually they all produce results but I need it to happen simultaneously. I did toy with the idea of doing them all separately but figure thats not very efficient. Any pointers would be appreciated.

Adrian Fischer
  • 119
  • 3
  • 10
  • I actually looked at that the other day for multi query problem and it solved it but I never noticed the last insert id part. Now that answer had killed two birds with one stone. – Adrian Fischer Apr 18 '16 at 07:05

1 Answers1

0
$sql= "INSERT INTO tbleClients (riskClientId, riskFacility, riskAudDate)     VALUES ('$riskclient2', '$facility2', '$riskdate2');";

After executing the above query, using mysqli_insert_id(), which gives you the last insert id.

So below query is useless. $sql .="SELECT LAST(riskId) FROM tbleClients;";

$sql .="INSERT INTO tblRiskRegister (riskId)     SELECT riskId FROM tbleClients ;";

You can insert last_insert_id in above query.

Unable to find the relation between above & below query.

$sql .= "INSERT INTO tblRiskRegister     (riskAudDate, riskClientId,       riskSessionId, RiskNewId) VALUES     ('$riskdate2', '$riskclient2', '$sessionid', '$risknewid')";
Dipanwita Kundu
  • 1,637
  • 1
  • 9
  • 14