在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