在MySQLi中多重插入有困難。我有這個數據庫,它由6個不同的表格組成,每個表格都有eid
作爲foreign key
從employees
表格。下面是表列表:employees
(這ofcourse持有primary key
爲eid
),然後contact
,education
,job_desc
,work_history
,familybg
什麼時遇到的麻煩是,當我試圖插入從形式採取了數據的索引頁面指向insert.php,其中MySQLi函數已被調用。 你可以看到下面的代碼:
[注:以下屬性僅僅是虛設。]
insert.php(修訂)
include('db.php');
//build sql statements
<?php
$sql1 = "INSERT INTO employee (fname,mname,
lname,age,
gender,birthday,
birthplace,citizenship,
status,sss,
philhealth,tin,
height,weight)
VALUES
('$fname','$mname','$surname',
'$age','$gender',
'$birth','$place',
'$citizen','$civil',
'$ss','$phil','$tin',
'$height','$weight')";
$r1 = mysqli_query($db,$sql1);
$id = mysqli_insert_id($db);
$sql2 = "INSERT INTO contact (eid,address,province,postcode,telno,mobile,email,alternate)
VALUES('$id','$address','$province','$postcode','$tel','$mob','$email','$alter')";
$sql3 = "INSERT INTO educ (eid,elem,egrad,highschool,hgrad,college,cgrad) VALUES ('$id','$elem','$egrad','$high','$hgrad','$col','$cgrad')";
$sql4 = "INSERT INTO employment (eid,position,status,hireDate,job_desc,basic,salary) VALUES ('$id','$pose','$stat','$hstart','$dept','$pay','$salary')";
$sql5 = "INSERT INTO work (eid,company_name,position,desc,startDate,endDate) VALUES ('$id','$prev','$pold','$job','$sdate','$edate')";
$sql6 = "INSERT INTO family (eid,fatherName,motherName,sibling,spouse,children) VALUES ('$id','$dad','$mom','$kname','$spouse','$child')";
//returns 1 if sucessful and 0 if not
//mysqli_query($link,$query)
$r2 = mysqli_query($db,$sql2) or die(mysqli_error($db));
$r3 = mysqli_query($db,$sql3) or die(mysqli_error($db));
$r4 = mysqli_query($db,$sql4) or die(mysqli_error($db));
$r5 = mysqli_query($db,$sql5) or die(mysqli_error($db));
$r6 = mysqli_query($db,$sql6) or die(mysqli_error($db));
$sqlResult = $r2 && $r3 && $r4 && $r5 && $r6;
//commit the queries if no errors otherwise rollback
if(!$sqlResult){
//sqlResult = 0, thus there was a problem
mysqli_rollback($db);
echo "ERROR: Could not save data!";
}else{
//sqlResult = 1, no problem
mysqli_commit($db);
echo "Record saved!";
}
mysqli_close($db);
?>
輸出顯示:ERROR: Could not save data!
當我試圖運行該程序。它只意味着insert語句無法繼續,因此返回到mysqli_rollback(); 起初,我想也許它與引用有關,但經過十幾次檢查後,我終於不認爲它是罪魁禍首。但如果這不是問題,那麼我想知道它是什麼?你知道我只是MySQLi的初學者。所以如果任何人有更廣泛的知識,並會給我一些建議,將不勝感激。
(電流)問題2:
經過長期的一系列的調試,該mysqli multiple insert
最後的工作原理與外鍵除外。當我檢查表contact
這是employees
表旁邊eid
列eid
成功記錄從employees
表eid
的確切值,但表中的其餘部分顯示0爲eid
列。任何人知道如何處理它?提前致謝。
注意:Kindle會檢查上面修改的代碼以查看更改並查看代碼當前的問題。
您應該使用準備好的語句。你能找出哪個語句給出了錯誤? – Jens 2014-08-30 07:28:47
@Jens現在有問題了'mysqli_insert_id();'它似乎沒有從eid的原始表中獲取值。這就是爲什麼除了「僱員」表之外沒有別的東西可以顯示。即使我這樣做了'mysqli_insert_id($ db);' 現在該怎麼辦? – Archangel08 2014-09-02 02:17:05