Bxx
Bxx

Reputation: 1625

MySQL Auto Increment No Duplicate

If I run the below query then use the AUTO_INCREMENT variable to post to table1 right afterwards, what are the chances that 2 users run the query at the same time and obtain identical auto increment values?

Is it very unlikely that this would happen?

$query = "SELECT AUTO_INCREMENT
              FROM  INFORMATION_SCHEMA.TABLES
              WHERE TABLE_SCHEMA = 'db1'
              AND   TABLE_NAME   = 'table1'";

$result =  $link->query($query);
$numRows = mysqli_num_rows($result);

while($var2 = mysqli_fetch_array($result)) {

   $autoIncr = $var2['AUTO_INCREMENT'];
}



$query = "INSERT INTO table1(id,firstName)
          VALUES('$autoIncr','$firstName')";

Upvotes: 0

Views: 69

Answers (2)

Bxx
Bxx

Reputation: 1625

Here's my answer to get a unique AI value:

$query = "INSERT INTO table1(id,firstName)
          VALUES('','$firstName')";

$result =       $link->query($query);
$autoIncr =     $link->insert_id;   //Gets id of last inserted row

Upvotes: 0

Drew
Drew

Reputation: 24970

Rather like

create table table1
( 
  id int auto_increment primary key,
  fullName varchar(100) not null
);

Then in the inserts

insert table1 (fullName) values('Fred Smith');

Upvotes: 2

Related Questions