简体   繁体   English

在插入多个表的情况下表索引干扰

[英]Table indexing interference in case of inserting into multiple tables

I'm working on a PHP user registration script, and for some reasons I don't want to insert all of user inputs in one table, so I split the table into a few smaller ones, and here is my code: 我正在使用PHP用户注册脚本,由于某些原因,我不想将所有用户输入都插入一个表中,因此我将该表分为几个较小的输入,这是我的代码:

<?php

$conn->autocommit(FALSE);

$stmt1 = $conn->prepare("INSERT INTO members (username,password,salt) VALUES (?,?,?);");
$stmt2 = $conn->prepare("INSERT INTO members_details (first_name,last_name,gender) VALUES (?,?,?);");
$stmt3 = $conn->prepare("INSERT INTO members_following DEFAULT VALUES;");
$stmt4 = $conn->prepare("INSERT INTO members_skills DEFAULT VALUES;");

$stmt1->bind_param("sss",$username,$hashed_password,$salt);
$stmt2->bind_param("ssi",$first_name,$last_name,$gender);
$stmt1->execute();
$stmt1->close();
$stmt2->execute();
$stmt2->close();
$stmt3->execute();
$stmt3->close();
$stmt4->execute();
$stmt4->close();

$conn->close();
?>

Q1: All of the tables have an auto increment uid. Q1:所有表都有一个自动增量uid。 I know that sql queries are done sequentially, but If two people register at the same time, is it possible that one of the users get the other one's uid? 我知道sql查询是顺序执行的,但是如果两个人同时注册,一个用户是否有可能获得另一个uid?

Q2: Is it possible that one of the queries in the series leads to an error for the first user and the next user gets a wrong uid? 问题2:该系列中的一个查询是否有可能导致第一个用户出错,而下一个用户得到了错误的uid? Is there anything I can do to rollback the changes made to the database in case of such error? 如果发生这种错误,我有什么办法可以回滚对数据库所做的更改?

I did some digging, and came up with an idea. 我做了一些挖掘,然后想到了一个主意。 I guess this is a more legitimate approach to consider: 我认为这是一种更合理的考虑方法:

I should create a "members" table with an auto increment id. 我应该创建一个具有自动增量ID的“成员”表。 Run the first query which is: 运行第一个查询,即:

"INSERT INTO members (username,password,salt) VALUES (?,?,?);"

Therefore I get the auto generated id by mysqli_insert_id(), then I'll run the next queries using the generated id. 因此,我通过mysqli_insert_id()获得了自动生成的ID,然后将使用生成的ID运行下一个查询。 So my code would be something like this: 所以我的代码将是这样的:

$stmt1 = $conn->prepare("INSERT INTO members (username,password,salt) VALUES (?,?,?);");

$stmt1->bind_param("sss",$username,$hashed_password,$salt);
$stmt1->execute();
$stmt1->close();

$generated_id = mysqli_insert_id($conn); //returns auto generated id in stmt1


$stmt2 = $conn->prepare("INSERT INTO members_details (uid,first_name,last_name,gender) VALUES (?,?,?,?);");

$stmt2->bind_param("issi",$generated_id,$first_name,$last_name,$gender);
$stmt2->execute();
$stmt2->close();
$conn->close();
?>

So the id for each user remains unique, and there is no chance that a user get an id which is generated for another user. 因此,每个用户的ID保持唯一,并且一个用户没有机会获得为另一个用户生成的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM