简体   繁体   中英

Uploading Large CSV File into Mysql Database

I want to upload large CSV document into mysql database can anyone help me out, the table consist of 10 fields but i want to upload into only 5 fields of the table without a heading. I want this done with php in the browser

$filename = $_FILES['sel_file']['tmp_name'];
<?php
    if($_FILES["file"]["type"] != "application/vnd.ms-excel"){
       die("This is not a CSV file.");
    }
    elseif(is_uploaded_file($_FILES['file']['name'])){
     $dbhost = 'localhost';
     $dbuser = 'root';
     $dbpass = '';
     $dbname = 'cbt_software';
     $link = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error        connecting to mysql server');
   mysql_select_db('cbt_software') or die(mysql_error());
   //Process the CSV file
   $handle = fopen($_FILES['file']['name'], "r");
   $data = fgetcsv($handle, 1000, ";"); 
   while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
      $att0 = mysql_real_escape_string($data[0]);
      $att1 = mysql_real_escape_string($data[1]);
      $att2 = mysql_real_escape_string($data[2]);
      $att3 = mysql_real_escape_string($data[3]);
      $att4 = mysql_real_escape_string($data[4]);  

      $sql = "INSERT INTO `course_reg` (`coursecode`,`coursename`,`coursedescription`,`coursemaster`,`courselevel`)VALUES     ('$att0','$att1','$att2','$att3','$att4')";
      mysql_query($sql) or die(mysql_error());
   }
   mysql_close($link);
   echo "CSV file successfully imported.";
}
else{
   die("You shouldn't be here");
}
?>

At first this imported all the field from the csv into just one field in the database and after i tampered with the code it is not recognicing it asa CSV file.

If you have the appropriate permissions, you can do so directly in MySQL with the LOAD DATA INFILE command, see http://dev.mysql.com/doc/refman/4.1/en/load-data.html or the mysqlimport utility, see http://dev.mysql.com/doc/refman/4.1/en/mysqlimport.html

Both methods will allow you to specify which columns the data should go in, for instance:

LOAD DATA INFILE 'myfile.txt' INTO TABLE 'mytable' (col1, col2, col3, ...)

or

mysqlimport --columns='col1,col2,...' tablename.csv

If you intend to do it from PHP, you should be able to read each line of the CSV file and execute an appropriate SQL INSERT query naming the appropriate columns (although that will not be as efficient as doing it directly in MySQL).

EDIT: I should add that you haven't mentioned what you've tried so far or what you're finding difficult; if you're stuck on something in particular, rather than just looking for suggestions on how to go about doing it, please update the question to say so.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM