更新2个表中的值,其中值互相引用

时间:2013-06-20 22:11:02

标签: php mysql database

我有2个表,我试图将值插入。

表1:

CREATE TABLE `subusers` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`UserId` bigint(20) NOT NULL,
`BranchId` bigint(20) NOT NULL,
 `Username` varchar(30) NOT NULL,
`Password` char(64) NOT NULL,
`Salt` char(64) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB

表2:

CREATE TABLE `branch` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`BusinessId` bigint(20) NOT NULL,
`UserId` bigint(20) NOT NULL,
`Name` varchar(30) NOT NULL,
`Info` varchar(300) NOT NULL,
PRIMARY KEY (`id`),
KEY `UserId` (`UserId`),
KEY `BusinessId` (`BusinessId`)
) ENGINE=InnoDB
ALTER TABLE `branch`
ADD CONSTRAINT `branch_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `subusers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

我正在尝试使用插入查询向表中添加值,其中我需要列subusers.branchid = branch.id AND branch.userid = subuser.id。通过我的查询插入数据后,我得到的结果是subuser.branchid = x-1 AND branch.userid = x-1 WHERE x是插入的最新行的id。

E.g  表SubUSers

----------------------------------------
|id |UserId|BranchId|Username|Password |
-----------------------------------------
|22 |    2  |    0   | Add    |  Add   |<--1st insert
---------------------------------------
| 23|    2  |    0   | Add    |  Add   |<--2nd insert(Branch id should be 23)
---------------------------------------
| 24|    2  |    23  | DER    |  DER   |<--3rd insert(Branch id should be 24)
---------------------------------------

表格分支

-----------------------------------
|id |BusinessId|UserId|Name|Info  |
-----------------------------------
|NIL|  NIL  |    NIL  | NIL | NIL | <---First Insert
-----------------------------------
|23 |    1  |    22   | Add |  Add| <---2nd Insert(UserId should be 23)
-----------------------------------
|24 |    1  |    22   | DER |  DER| <---3rd insert(UserId should be 24)
-----------------------------------

在第一次插入时,我收到错误:

 Cannot add or update a child row: a foreign key constraint fails (`kenced`.`branch`, CONSTRAINT `branch_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `subusers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

在后续尝试中,插入查询有效,但Subusers.branchid和branch.userid的值是错误的。

My Code:

<?PHP
session_start();

if(@$_SESSION['Auth']!=="Yes" AND @$_SESSION['Type']!=="Admin")
{
echo"You are not authorised to view this page.Please click <a href='Login.php'>here</a> to login.";
exit();
}
?>

<?PHP

if(@$_POST['adduser']=="Submit")
{
include("cxn.inc");
$userid=$_SESSION['UserId'];
$username=$_POST['username'];
$username=mysqli_real_escape_string($cxn,$username);
$password=$_POST['password'];
$password=mysqli_real_escape_string($cxn,$password);
$name=$_POST['name'];
$name=mysqli_real_escape_string($cxn,$name);
$info=$_POST['info'];
$info=mysqli_real_escape_string($cxn,$info);
//gets business id
$getbId="SELECT id FROM Business Where Userid='$userid'";
$runbId=mysqli_query($cxn,$getbId) or die (mysqli_error($cxn));
$fetchBid=mysqli_fetch_assoc($runbId);
$bId=$fetchBid['id'];
//get subuserid
$getsid="SELECT id FROM SubUsers WHERE UserId='$userid'";
$runsid=mysqli_query($cxn,$getsid) or die (mysqli_error($cxn));
$fetchsid=mysqli_fetch_assoc($runsid);
$sid=$fetchsid['id'];
//get BranchId
$getbrid="SELECT id FROM Branch WHERE UserId='$sid'";
$runbrid=mysqli_query($cxn,$getbrid) or die (mysqli_error($cxn));
$fetchbrid=mysqli_fetch_assoc($runbrid);
$brid=$fetchbrid['id'];

//adds to table subuser
$adduser="INSERT INTO SubUsers (BranchId,UserId,Username,Password) VALUES ('$brid','$userid','$username','$password')";
$runuser=mysqli_query($cxn,$adduser) or die(mysqli_error($cxn));
//adds to table branch
$addbranch="INSERT INTO Branch (UserId,BusinessId,Name,Info) VALUES ('$sid','$bId','$name','$info')";
$runbranch=mysqli_query($cxn,$addbranch) or die (mysqli_error($cxn));
//gives success message upon successfully adding the user
$success="User Successfully added";
}


?>

<html>
<head><link rel="stylesheet" type="text/css" href="style.css" /></head>
<body>
<?PHP //include("AdminNav.php");?>
<form action="<?PHP echo $_SERVER['PHP_SELF']?>" name="AddUser" method="POST">
<table border="1">
<tr><td>Username</td><td><input type="text" name='username' size='38' maxlength='40'/></td></tr>
<tr><td>Password</td><td><input type="password" name="password" size="38" maxlength="64" /> </td></tr>
<tr><td>Branch Name</td><td><input type="text" name='name' size='38' maxlength='40'/></td></tr>
<tr><td>Branch Info</td><td><textarea name="info" rows="10" cols="30"></textarea></td>    </tr>
<tr>
<td><input type="Submit" name="adduser" value="Submit" /></td>
<td><?PHP if(isset($success)){echo"$success";} ?></td>
</tr>



</form>
</table>
</body>
</html>

我正在考虑使用SELECT MAX(id)+ 1来获取当前的id。

从我能够读到的LAST_INSERT_ID开始,它不会起作用,因为我只使用1个查询一次插入所有值,因此,没有&#34;最后一次查询&#34;。

有人可以指出我正确的方向吗?

由于

PS:我正在使用PHP和MySQL。

编辑: 我已尝试添加分隔查询,最后添加ID。但这不起作用,因为我收到错误

Cannot add or update a child row: a foreign key constraint fails (`kenced`.`branch`, CONSTRAINT `branch_ibfk_1` FOREIGN KEY (`UserId`) REFERENCES `subusers` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)

我的代码:

mysqli_autocommit($cxn,"FALSE");
//adds to table subuser
$adduser="INSERT INTO SubUsers (UserId,Username,Password) VALUES ('$userid','$username','$password')";
//$runuser=mysqli_query($cxn,$adduser) or die(mysqli_error($cxn));
//adds to table branch
$addbranch="INSERT INTO Branch (BusinessId,Name,Info) VALUES ('$bId','$name','$info')";
//$runbranch=mysqli_query($cxn,$addbranch) or die (mysqli_error($cxn));

$runuser=mysqli_query($cxn,$adduser) or die(mysqli_error($cxn));
$sid=mysqli_insert_id($cxn);
$runbranch=mysqli_query($cxn,$addbranch) or die (mysqli_error($cxn));
$brid=mysqli_insert_id($cxn);
$addsid="INSERT INTO Branch(UserId) VALUES ('$sid')";
$runsid=mysqli_query($cxn,$addsid) or die (mysqli_error($cxn));
$addbrid="INSERT INTO SubUsers(BranchId) VALUES ('$brid')";
$runbrid=mysqli_query($cxn,$addbrid) or die (mysqli_error($cxn));
if($runsid and $runbrid)
mysqli_commit($cxn);
else
{
mysqli_rollback($cxn);
echo"ROLLBACKED";
}
//gives success message upon successfully adding the user
$success="User Successfully added";

我尝试做的是同时插入查询以及查询的ID。但是,mysqli_insert_query失败,因为我收到错误无法添加或更新子行:外键约束失败( kencedbranch,CONSTRAINT branch_ibfk_1 FOREIGN KEY(UserId)引用subusersid)ON DELETE CASCADE ON UPDATE CASCADE)。

有人可以帮我一把吗?

非常感谢。

0 个答案:

没有答案