我有一段代码循环遍历一系列sql查询,如下所示:
$cached_queries = array();
foreach ($queries as $index => $query2)
{
$query2 = trim($query2);
if ($query2 != "")
{
if (isset($cached_queries[$query2]))
{
$err_msg = $index . ": query [$query2] has already been executed on " .
"index [" . $cached_queries[$query2] . "]!";
die($err_msg);
}
else
{
$cached_queries[$query2] = $index;
print "$index: executing query: [$query2]<br>" . PHP_EOL;
$db->query($query2);
}
}
}
它适用于变量名$ query2,但如果我将其更改为$ query。该脚本尝试执行第二次到最后一次查询并使用错误消息执行,指出在执行最后一个语句时已经执行了倒数第二个语句(第84个索引)。
...
84: executing query: [INSERT INTO `world_bank_incomes` (`id`, `name`) VALUES (1, 'Low-income'), (2, 'Lower-middle-income'), (3, 'Upper-middle-income'), (4, 'High-income');]
85: query [INSERT INTO `world_bank_incomes` (`id`, `name`) VALUES (1, 'Low-income'), (2, 'Lower-middle-income'), (3, 'Upper-middle-income'), (4, 'High-income');] has already been executed on index [84]!
请解释为什么对变量名称进行简单更改可让脚本按预期工作。
背景信息
最后一个查询是:
INSERT INTO `world_bank_regions` (`id`, `name`) VALUES (1, 'East Asia and Pacific'), (2, 'Europe and Central Asia'), (3, 'Latin America & the Caribbean'), (4, 'Middle East and North Africa'), (5, 'South Asia'), (6, 'Sub-Saharan Africa');
使用$ query变量直接复制原始'破损'代码:
$cached_queries = array();
foreach ($queries as $index => $query)
{
$query = trim($query);
if ($query != "")
{
if (isset($cached_queries[$query]))
{
$err_msg = $index . ": query [$query] has already been executed on " .
"index [" . $cached_queries[$query] . "]!";
die($err_msg);
}
else
{
$cached_queries[$query] = $index;
print "$index: executing query: [$query]<br>" . PHP_EOL;
$db->query($query);
}
}
}
$ query到达此部分代码的第一行之前的值是:
INSERT INTO `world_bank_regions` (`id`, `name`) VALUES (1, 'East Asia and Pacific'), (2, 'Europe and Central Asia'), (3, 'Latin America & the Caribbean'), (4, 'Middle East and North Africa'), (5, 'South Asia'), (6, 'Sub-Saharan Africa');
我知道重复使用变量是不好的做法但是在这种情况下应该不会产生影响吗?
框架:codeigniter(所以$ db是CI mysql驱动程序)。
查询在代码部分之前用作参考:
foreach ($queries as &$query)
{
$query = trim($query);
if ($query != "")
{
$query = "INSERT " . $query;
}
}
$cached_queries = array();
...