Forum Moderators: coopster

Message Too Old, No Replies

Extra element got inserted into the table PHP array and mysql insert

         

shwebamar001

6:27 pm on Aug 16, 2009 (gmt 0)

10+ Year Member



I am new to PHP and need some help in troubleshooting the issue below.

examLocations is the array which holds the locations of exams being held, for example: ("San Jose, CA" "Santa Clara, CA") print_r properly print the two locations within the array, the problem I am having is when inserting into the table the last element in the array got inserted twice, basically instead of two rows being inserted to the mySQL table, 3 rows got inserted with "Santa Clara, CA" repeated twice. It doesn't matter if I use the foreach as well.

While usuage:

print_r($examLocations);
while (list(, $location) = each($examLocations)) {
echo $location;
$query2 = "INSERT INTO EXAMINATION_LOCATION_T SET
Exam_ID = '$mexamID',
Location_Name = '$location'";

mysql_query($query2) or die (mysql_error());
mySleep(0.5);
}

Foreach:

foreach ($examLocations as &$location) {
$location = trim ($location);
if ($location) {
$query2 = "INSERT INTO EXAMINATION_LOCATION_T SET
Exam_ID = '$mexamID',
Location_Name = '$location'";

mysql_query($query2) or die (mysql_error());
mySleep(0.5);
}
}

IanKelley

9:24 pm on Aug 16, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I have some questions about your code:

while (list(, $location) = each($examLocations)) { 

This would imply that $examLocations is a multi-dimensional array correct?

Exam_ID = '$mexamID', 

Assuming that $examLocations is multidimensional, presumably $mexamID should be assinged by the list() above but it is not, instead it is dropped by the lack of variable before the comma. Right?

foreach ($examLocations as &$location) { 
$location = trim ($location);

Because $examLocations is a multi-dimensional array wouldn't the value of $location be an array? But it seems you are accessing it as a variable.

Also I don't understand why you are accessing $location by reference in the loop?

[edit: clarity]

shwebamar001

5:00 am on Aug 17, 2009 (gmt 0)

10+ Year Member



Actually they are single dimensional array.

Here is the output of the print_r and echo of $location for both while and foreach loop.

Array ( [0] => Detriot, MI [1] => Durham, NC )
While Loop
Detriot, MI

While Loop
Durham, NC

Foreach Loop
Detriot, MI

Foreach Loop
Durham, NC

IanKelley

5:15 am on Aug 17, 2009 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



Ah ok, that makes more sense. Unfortunately I'm not seeing anything in your loop that would cause the same location to be inserted into the database twice.

shwebamar001

5:20 am on Aug 17, 2009 (gmt 0)

10+ Year Member



Oops, figure that out, forgot to delete the mysql_query outside of the loop.