简体   繁体   中英

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

$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. 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?

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? 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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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