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

时间:2016-04-13 15:30:32

标签: php mysql mysqli transactions

是否可以获取前两个查询的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值?

1 个答案:

答案 0 :(得分:0)

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;