I have a section of code that loops through an array of sql queries like so:
$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);
}
}
}
It works with the variable name $query2, but if I change that to $query. the script tries to execute the second to last query twice and dies with the error message, stating that the second to last statment (84th index) has already been executed when executing the last statement.
...
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]!
Please explain why a simple change to the variable name allows the script to work as expected.
Context Information
the last query is:
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');
A direct copy of the original 'broken' code using the $query variable:
$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);
}
}
}
The value of $query before it reaches the first line of this section of code is:
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');
I know it's bad practice to re-use variables but it shouldn't have an affect in this situation should it?
Framework: codeigniter (so $db is the CI mysql driver).
Query is used as a reference just before the code section:
foreach ($queries as &$query)
{
$query = trim($query);
if ($query != "")
{
$query = "INSERT " . $query;
}
}
$cached_queries = array();
...