Saturday 8 June 2013

wierd bug when reading from a csv file and importing data into mysql using php

wierd bug when reading from a csv file and importing data into mysql using php

Okay so I have a php script to insert data into a mysql table it looks like this:
<?php
$connect = mysql_connect('localhost',my_username','my_pass');
if (!$connect) {die('Could not connect to MySQL: ' . mysql_error());}
$cid =mysql_select_db('geolocation',$connect);
// supply your database name
define('CSV_PATH','/var/www/geolocation/');
// path where your CSV file is located
$csv_file = CSV_PATH . "new_Location.csv"; // Name of your CSV file
$csvfile = fopen($csv_file, 'r');
$theData = fgets($csvfile);
$i = 0;
$k = 0;
while (!feof($csvfile)) {
   $csv_data[] = fgets($csvfile, 1024);
   $csv_array = explode(",", $csv_data[$i]);
   $insert_csv = array();
   if(isset($csv_array[0]) && isset($csv_array[1]) &&  isset($csv_array[2]) &&  isset($csv_array[3]) &&  isset($csv_array[4]) &&  isset($csv_array[5]) &&  isset($csv_array[6]) &&  isset($csv_array[7]) &&  isset($csv_array[8])){
     $insert_csv['ID'] = $csv_array[0];
     $insert_csv['country'] = $csv_array[1];
     $insert_csv['region'] = $csv_array[2];
     $insert_csv['city'] = $csv_array[3];
     $insert_csv['postalCode'] = $csv_array[4];
     $insert_csv['latitude'] = $csv_array[5];
     $insert_csv['longitude'] = $csv_array[6];
     $insert_csv['other'] = $csv_array[7];
     $insert_csv['another'] = $csv_array[8];
     $query = "INSERT INTO City (locId, country, region, city, postalCode, latitude, longitude) VALUES('".$insert_csv['ID']."','".$insert_csv['country']."','".$insert_csv['region']."','".          $insert_csv['city']."','".$insert_csv['postalCode']."','".$insert_csv['latitude'].",,'".$in sert_csv['longitude']."'')";
  $n=mysql_query($query, $connect );
   $i++;
   }
   if($k==1000){
    echo $i . " \n";
    $k = 0;
   }
   $k++;
}
fclose($csvfile);
echo "File data successfully imported to database!!";
mysql_close($connect);
?>
now when I run the script everything seems to work properly and I get echo $i every once in a while and eventually the script ends with no errors or anything however when I look into my mysql (through phpmyadmin) I do not see any of the rows added to the table... I have also used another modified version of this script in the past and it worked perfectly (other than slow), However I'm still pretty green when it comes to mysql and can't seem to figure out what's going on... here is my table format
 locId --> int(11)
 country --> varchar(2)
 region --> varchar(2)
 city --> varchar(50)
 postalCode --> varchar(8)
 latitude --> varchar(10)
and also a sample from the csv file:
 46,CK,NA,NA,NA,-21.2333,-159.7667,NA,NA
any help with why this isn't workign or even how I can go about debugging it would be very much appreciated!
also note (I do not wish to have the last to value in the csv in my table) so those are ommited from the insert statement on purpose

No comments:

Post a Comment