gpt4 book ai didi

php - MYSQL 不同步自动增量

转载 作者:行者123 更新时间:2023-11-29 07:50:11 25 4
gpt4 key购买 nike

我正在使用的一个表上有一个奇怪的行为,我不确定是我的 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

但是如果我在名称和汽车上放置唯一索引,自动增量就会不同步,我无法理解为什么,因为我看不到我的 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

最佳答案

您认为为什么不同步? John 的丰田车 ID 仍为 3,他的沃尔沃车 ID 为 1

如何获得结果?您只需SELECT您的汽车,对吗?该行为很好,因为无需使用任何 ORDER BY 语句即可按 id 对数据进行排序。

您应该使用SELECT id, name, cars FROM cars ORDER BY id ASC进行查询。

mysql返回无序列表是完全没问题的。 “无序”只是一些内部优化的结果。

关于php - MYSQL 不同步自动增量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26676833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com