I have a weird behavior on one of the tables I am working with, I am not sure if it is my php code or some setting on the database that is causing auto incremented id's to fall out of sync.
If I run the following code without any indexes on name&cars I get:
$cars = array("Volvo","BMW","Toyota");
$name = "John Smith";
foreach($cars as $value)
{
try
{
//insert into database with a prepared statement
$query = $db->prepare(
'INSERT INTO cars (name,cars)
VALUES (:name,:cars)
');
$query->execute(array(
':name' => $name,
':cars' => $value
));
}
//else catch the exception and show the error.
catch(PDOException $e)
{
$error[] = $e->getMessage();
}
}
///Results
id || name || cars
1 || John Smith || Volvo
2 || John Smith || BMW
3 || John Smith || Toyota
But if I put an unique index on name&cars, the auto increment gets out of sync and I can't understand why because I can't see anything wrong with my PHP code?
$cars = array("Volvo","BMW","Toyota");
$name = "John Smith";
foreach($cars as $value)
{
try
{
//insert into database with a prepared statement
$query = $db->prepare(
'INSERT INTO cars (name,cars)
VALUES (:name,:cars)
');
$query->execute(array(
':name' => $name,
':cars' => $value
));
}
//else catch the exception and show the error.
catch(PDOException $e)
{
$error[] = $e->getMessage();
}
}
///Results
id || name || cars
3 || John Smith || Toyota
1 || John Smith || Volvo
2 || John Smith || BMW