Hi All
I'm sure I'm missing something very small - and embarrassing!
I'm being lazy - I could have entered the data manually, but wanted to automate it.
I have a small csv file containing swimming meets, dates and locations along the following lines:
May-13;;;;
17;other;Level 1 Program 1;Arboretum;
24;other;All Levels Program 2;King's Park;
June-13;;;;
15;other;Level 2 3 Program3;Pmb;
.
. and so forth
I read this into an array, run through the array to correct the date format and then insert each line into a mySQL database table.
All easy, but my code is inserting multiple entries for each key in the array! Sometimes it inserts 6 records for each key and sometimes 19. It jsut seems to be quite random!
My code:
//===== Read csv into array =====
if (($handle = fopen("../uploads/KZNCal.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$Cal[] = $data;
}
fclose($data);
}
$con = new mysqli($HOST, $USER, $PASS, $NAME);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = $con->prepare("INSERT INTO `kzn_upcoming` (`meet_name`, `location`, `start_date`) VALUES (?, ?, ?)");
foreach ($Cal as $Key => $Event) {
//===== First 2 rows not needed =====
if ($Key > 1) {
if (!is_numeric(substr($Event[0], 0, 1))) {
//===== Get month and year =====
$Month = date('m', strtotime(substr($Event[0], 0, 3)));
$Year = '20' . substr($Event[0], 4);
}
else {
$Day = trim(substr($Event[0], 0, 2));
if ($Day < 10) {$Day = '0' . $Day;}
// === Discarded $Event[1] - of no consequence for this table. ===
$Name = $Event[2];
$Location = $Event[3];
$Start = "$Year-$Month-$Day";
//===== Inserted into "clean" array to see if there was something wrong =====
$Calendar[] = array($Name, $Location, $Start);
}
}
}
echo "<br>Count: " . count($Calendar) . "<br>"; //===== Produces expected result of 39 =====
$query = $con->prepare("INSERT INTO `kzn_upcoming` (`meet_name`, `location`, `start_date`) VALUES (?, ?, ?)");
foreach ($Calendar as $Key => $Meet) {
echo "$Key: $Meet[0] - $Meet[1] - $Meet[2]<br>"; //===== All displayed correctly =====
$query->bind_param("sss", $Meet[0], $Meet[1], $Meet[2]);
$query->execute();
}
$query->close();
$con->close();
There are a whole 39 rows in the $Calendar array. The echo produces the expected result - 39 rows, as per the count(). I get random duplication of each record inserted into the table! One run, I had 91 records for each Meet, another "only" 6!
What have I missed?