0

Hi,

I want to import only zip codes (inside csv) into one of table inside mysql database. All zip codes are in a csv file. When I run PHP code it works only with first zip code. Can somebody please help me on this where I am doing mistake.

Here is CSV data format

177383
172828
263883
388388

Here is PHP code

<?php
if(isset($_POST['sub']))
{



$ch = $_POST['chan'];
echo $ch;

     if (!file_exists("csvfiles/" . $_FILES["file"]["name"]))
      {
      move_uploaded_file($_FILES["file"]["tmp_name"], "csvfiles/" . $_FILES["file"]["name"]);
      }




define('CSV_PATH','/home/woodpell/public_html/csvfiles/');
// path where your CSV file is located

$csv_file = CSV_PATH . $_FILES["file"]["name"]; // Name of your CSV file



if ($getfile = fopen($csv_file, "r")) { 
        $data = fgetcsv($getfile, 1000, ",");
        while ($data = fgetcsv($getfile, 1000, ",")) {
         $num = count($data); 

         for ($c=0; $c < $num; $c++) {
             $result = $data; 

             $str = implode(",", $result); 

             $slice = explode(",", $str);
             $col1 = $slice[0]; 

// SQL Query to insert data into DataBase

$query = mysql_query("INSERT INTO csvtbl(ID,name,city) VALUES('".$col1."','".$col2."','".$col3."')");

$s=mysql_query($query, $connect ); 
     }
   } 
  }



// fclose($csv_file);

echo "done";
mysql_close($connect);
}
?>
<form method="post" enctype="multipart/form-data">
<label for="chan">Channel ID<input type="text" name="chan" id="chan"><br />
<label for="file">File<input type="file" name="file" id="file"><br />
<input type="submit" name="sub" id="sub">
</form>
2
Contributors
1
Reply
15
Views
4 Years
Discussion Span
Last Post by cereal
0

Start by removing this at line 26 remove:

$data = fgetcsv($getfile, 1000, ",");

You don't need it because the same runs on line 27, in the while statement. Remove also line 42, since the previous query is already using mysql_query().

Two suggestions:

  1. avoid using MySQL library, and move to MySQLi or PDO, the former is going to be removed from PHP
  2. when you insert, consider to pack multiple values('a','b','c'), ('d','e','f'), ('g', 'h', 'i'), ... statements in order to reduce the amount of write queries to your database, because if you're going to import large numbers of csv lines, you will generate a lot of traffic and locks.

Edited by cereal

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.