【发布时间】:2014-12-27 21:37:36
【问题描述】:
我正在使用的其中一个表上有一个奇怪的行为,我不确定是我的 php 代码还是数据库上的某些设置导致自动递增的 id 不同步。
如果我在名称和汽车上没有任何索引的情况下运行以下代码,我会得到:
$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
但是,如果我在 name&cars 上放置一个唯一索引,自动增量就会不同步,我不明白为什么,因为我看不到我的 PHP 代码有任何问题?
$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
【问题讨论】:
-
除非您的 SELECT 语句有 ORDER BY 子句,否则不保证您的记录将按任何特定顺序返回
-
为什么要 name / cars 成为唯一索引?
-
我只想要一个名字和汽车的组合。除此之外,对我来说没有任何用处,因为我只会获得与该人拥有这辆命名汽车相同的信息,其他所有内容都将作为副本存在于数据库中
-
也谢谢你告诉我,我一直以为记录是按顺序插入的。所以我不应该担心我做错了什么导致订单失败?
标签: php mysql auto-increment sql-insert