Ripon
Ripon

Reputation: 81

same Unique ID for upload data from csv to mysql table

I am trying to import data from csv file to mysql table.from below code i am able to import my csv data to mysql table. In that mysql table there is a column called "ord" which should have same unique ID (need to increment by one) for each time during data upload from csv to mysql table. i tried by update query but after increment once it is giving the same unique number to other next uploading . Not sure where i made wrong and need your advice to correct my code.

$connect = mysql_connect('localhost','root','');

if (!$connect) {
 die('Could not connect to MySQL: ' . mysql_error());
}

//your database name
$cid =mysql_select_db('upload',$connect);

// path where your CSV file is located
define('CSV_PATH','D:/');

// Name of your CSV file
$csv_file = CSV_PATH . "Book1.csv"; 


if (($handle = fopen($csv_file, "r")) !== FALSE) {
   fgetcsv($handle);   
   while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        for ($c=0; $c < $num; $c++) {
          $col[$c] = $data[$c];
        }

 $col1 = $col[0];
 $col2 = $col[1];
 $col3 = $col[2];
 $col4 = $col[3];
  $col5 = $col[4];
  
  // SQL Query to insert data into DataBase

$query = "INSERT INTO unique_entry(ord,size,colour,qty,Creation_Date) VALUES('".$col1."','".$col2."','".$col3."','".$col4."',now())";
$s     = mysql_query($query, $connect );
 }
 mysql_query("
    UPDATE unique_entry 
    SET ord= ' ".$col1." ' + 1 
    WHERE Creation_Date = now()
");
    fclose($handle);
}
echo "File data successfully imported to database!!";
mysql_close($connect);

Upvotes: 0

Views: 426

Answers (1)

Pujitha Vamsi
Pujitha Vamsi

Reputation: 143

You are writing the update query outside of while loop. So the query will not execute all the times. Only for the last entry it will update. So we can do two things. 1) Include that update query inside the while loop. 2) increment the $col1 value before insert query and execute query. Then it will work for all entries.

Upvotes: 1

Related Questions