Search code examples
phpmysqlinsertlast-insert-id

How to use Insert query with multiple tables at a same time?


I have one form let's say bill form. i have 3 tables.

  1. bill (billId->primary key)
  2. billdetails (billdetailId->primary key, billId-> foregin key)
  3. fintran (finalId -> primary key, there are total 10 inputs in form.

On submit first 5 input should go in bill table and other 5 input should go in bill details. And all will go in final table. i used below query for this.

BEGIN;
$sql = mysqli_query($conn,"INSERT INTO `bill`(`societyId`, `unitId`, `memberId`, `area`, `arrear`, `invoiceNumber`, `invoiceDate`, `dueDate`, `billingPeriod`, `total`, `interestOnArrear`, `totalDue`, `email`, `penalty`, `principalArrears`, `interestArrears`, `advancedAdjusted`, `netPending`) VALUES ('".$societyId."','".$unitId."','".$memberId."','".$area."','".$arrear."','".$invoiceNumber."','".$invoiceDate."','".$dueDate."','".$billingPeriod."','".$total."','".$interestOnArrear."','".$totalDue."','".$email."','".$penalty."','".$principalArrears."','".$interestArrears."','".$advancedAdjusted."','".$netPending."')");     
$memo = $_REQUEST['memo'];
$charge = $_REQUEST['charge'];
$sql= mysqli_query($conn,"INSERT INTO `billdetail`(`biilId`, `memo`, `charge`) VALUES (LAST_INSERT_ID(),'".$memo."','".$charge."')");
$sql= mysqli_query($conn,"INSERT INTO `fintran`(`societyId`, `docId`, `docTypeName`, `docDate`, `unitId`, `unitName`, `memberId`, `memberName`, `comboId`, `ledgerId`, `ledgerName`, `debit`, `credit`, `netValue`) VALUES ('".$societyId."',LAST_INSERT_ID(),'bill','','".$unitId."','".$unitId."','".$memberId."','".$memberId."','','".$charge."','','','','')");
COMMIT;

after insert data i want billId i.e primary key of bill table in both billdetails and fintran table. but with this query i'm able to get this in only billdetail table. In fintran table i get primary key of billdetail table. please help me with the same.


Solution

  • No, you can't insert into multiple tables in one MySQL command. You can however use transactions.

    Check this : MySQL Insert into multiple tables? (Database normalization?)