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


Here is PHP code


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

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

// 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";
<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">

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.
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.