gpt4 book ai didi

php - mysqli - 可以获取事务中之前两个查询的 insert_id 吗?

转载 作者:行者123 更新时间:2023-11-29 21:08:38 25 4
gpt4 key购买 nike

是否可以获得前两个查询的insert_id?我可以得到最后一张,但想要前两张。在下面的示例中,处理表单后,我想向地址表添加一个新角色,向角色表添加新行,然后使用前两个查询中插入的查询中的 id 添加一行到客户。这有可能吗?

if(isset($_POST["submit"])) :
$username = $_POST["username"];
$password = $_POST["password"];
$role = $_POST["role"];
$permission1 = intval($_POST["permission1"]);
$permission2 = intval($_POST["permission2"]);
$city = $_POST["city"];
$state = $_POST["state"];
mysqli_autocommit($connection,FALSE);
mysqli_query($connection,"INSERT INTO Address(city, state) VALUES('{$city}', '{$state}')");
mysqli_query($connection,"INSERT INTO Roles(roleName, permission1, permission2) VALUES('{$role}', '{$permission1}', '{$permission2}')");
mysqli_query($connection,"INSERT INTO Customers(username, password, roleId, addressId) VALUES ('{$username}', '{$password}'," . mysqli_insert_id($connection) . " , " . mysqli_insert_id($connection) . ")");
if(mysqli_error($connection)):
echo mysqli_error($connection);
endif;
mysqli_commit($connection);
endif;

最后一个查询中的mysqli_insert_id($connection)将从Roles插入中提取ID两次。有什么办法让它从前两个查询中获取两个 Id 值吗?

最佳答案

if(isset($_POST["submit"])) :
$username = $_POST["username"];
$password = $_POST["password"];
$role = $_POST["role"];
$permission1 = intval($_POST["permission1"]);
$permission2 = intval($_POST["permission2"]);
$city = $_POST["city"];
$state = $_POST["state"];
mysqli_autocommit($connection,FALSE);

mysqli_query($connection,"INSERT INTO Address(city, state) VALUES('{$city}', '{$state}')");
//this will give you first id//
$first_inserted_id = mysqli_insert_id($connection);

mysqli_query($connection,"INSERT INTO Roles(roleName, permission1, permission2) VALUES('{$role}', '{$permission1}', '{$permission2}')");
//this will give you second id//
$second_inserted_id = mysqli_insert_id($connection);

mysqli_query($connection,"INSERT INTO Customers(username, password, roleId, addressId) VALUES ('{$username}', '{$password}'," . $first_inserted_id . " , " . $second_inserted_id . ")");

//this will give you third id//
$third_inserted_id = mysqli_insert_id($connection);

if(mysqli_error($connection)):
echo mysqli_error($connection);
endif;
mysqli_commit($connection);
endif;

关于php - mysqli - 可以获取事务中之前两个查询的 insert_id 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36603101/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com