2012-05-15 57 views
0

如何在第一張表中插入一行,並在一個帖子中插入第二張表中的多行?如何將數據插入到一個帖子中的兩個表中?

我已經拖表中的第一個是主表和第二個是子表,例如:

1表 - >>發票 第2表 - >>sub_invoices

每張發票都鏈接到一個或多個子發票。

所以,我需要從一個崗位到拖桌子,一排數據插入到發票和一個或多個成sub_invoices

發票 :: invoice_iddatetotaldrvr_namemobilecar_notofromusername

sub_invoices :: invoice_idcontract_noinv_sub_nodestcontract_vluadvncd_sumlate_sumdiscount_extrarcvd_sumnotesjob_no

if(isset($_POST['addinvoice2']) and $_POST['addinvoice2'] == 'addinvoice2'){ 
      //invoices:: 
      $drvr_name = $_POST['drvr_name']; 
      $mobile = $_POST['mobile']; 
      $car_no = $_POST['car_no']; 
      $to = $_POST['to']; 
      //sub_invoices:: 
      foreach($_POST['contract_no'] as $index => $contractno) { 

        $contract_no = $contractno; 
        $inv_sub_no = $_POST['inv_sub_no'][$index]; 
        $dest = $_POST['dest'][$index]; 
        $contract_vlu = $_POST['contract_vlu'][$index]; 
        $advncd_sum = $_POST['advncd_sum'][$index]; 
        $late_sum = $_POST['late_sum'][$index]; 
        $discount_extra = $_POST['discount_extra'][$index]; 
        $rcvd_sum = $_POST['rcvd_sum'][$index]; 
        $notes = $_POST['notes'][$index]; 
        $job_no = $_POST['job_no'][$index]; 
      } 


       $date=date('d-m-y h:iA'); 

       $MAIN = mysql_query("INSERT INTO `invoices`(`invoice_id`, `date`, `total`, `drvr_name`, `mobile`, `car_no`, `to`, `from`, `username`) 
       VALUES 
       ('','$date','','$drvr_name','$mobile','$car_no','$to','','') 
       ") or die(mysql_error()); 



       $last_id_in_invoices = mysql_insert_id(); 

       $SUB = "INSERT INTO `sub_invoices` 
       (`invoice_id`, `contract_no`, `inv_sub_no`, `dest`, `contract_vlu`, `advncd_sum`, `late_sum`, 
       `discount_extra`, `rcvd_sum`, `notes`, `job_no`) 
       VALUES ($last_id_in_invoices,$contract_no,$inv_sub_no,$dest,$contract_vlu,$advncd_sum,$late_sum,$discount_extra,$rcvd_sum,$notes,$job_no)"; 



       $RESULT_SUB = mysql_query($SUB); 

       if (isset($MAIN, $RESULT_SUB)){ 
        die (" 
         <center>Done Successfully!</center> 
         "); 
       } 
      } 
+0

入住http://stackoverflow.com/questions/5178697/mysql-insert-into-multiple-tables-database-normalization – inhan

回答

0

敢肯定你會使用兩個INSERT語句,你爲什麼不這樣做?

INSERT INTO INVOICES.... and INSERT INTO SUB_INVOICES...(perhaps in a loop) 
+0

的acepted答案,我試着用循環多次,但失敗了,只有第一排在循環插入 –

+0

然後,我建議你仔細看看失敗的SQL語句 - 它似乎是錯誤的罪魁禍首 - 你知道那個錯誤是什麼嗎? – GDP

+1

另一種選擇是,儘管它超出了基本的mySQL,但是使用了可以更新兩者的存儲過程。 – GDP

相關問題