I have a list of various postal information. This data is within a mysql table called “postal_codes”.
I would like to add each row of this table into a local array for use in a script.
The problemt hat I am facing is that I keep getting errors relating to undefined variables within the while loop.
Here is the code I have so far:
// Get postal info and make into array
$postalCodes[] = array();
if ($stmt = $link->prepare("SELECT id, suburb, boxCode, streetCode, townName FROM postal_codes")) {
if (!$stmt->execute())
{
printf("failed to execute");
}
if (!$stmt->bind_result($id, $suburb, $boxCode, $streetCode, $townName))
{
printf("failed to bind params");
}
if (!$stmt->store_result())
{
printf("failed to store result");
}
while ($stmt->fetch())
{
$postalCodes['id'] += $id;
$postalCodes['suburb'] += $suburb;
$postalCodes['boxCode'] += $boxCode;
$postalCodes['streetCode'] += $streetCode;
$postalCodes['townName'] += $townName;
}
$stmt->close();
}
foreach ($postalCodes as $postalCode)
{
if ($postalCode['boxCode'] == 5850)
{
printf("{$postalCode['suburb']}");
}
}
Could someone by chance spot the problem with this code or suggest a way for me to code this procedure in a better way.
Any assistance and insight in this regard would be greatly appreciated, thanks!
The “error” is probably caused by your associative array:
Ask yourself: what is the value of
$postalCodes['id']the first time you call this? It still isn’t defined. So you can either initialize the variables beforehand, or you can switch off warnings of this type through error_reporting().EDIT: The array-issue
You want to do something like:
I think you were confused about the meaning of
+=. If you want to add an element to your array, you usearray[]=something.