读取多个csv并使用php从目录中插入mysql数据库

时间:2016-08-24 11:53:40

标签: php mysql csv

陷入了一段代码,需要一些见解。我在一个文件夹中有几个csv文件,需要将它们的数据插入到mysql中。 我试过这个post,但它不能用于多个文件。

以下是我的代码:

<?php

 //database connection details
 $connect = mysql_connect('localhost','test','pass');

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

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

  // path where your CSV file is located
   define('CSV_PATH','/root/path/uploads/');

  // Name of your CSV file


   $filename= "1";



  do {
echo $filename;
$filename++;
$csv_file = CSV_PATH . $filename.".csv";  




  if (($handle = fopen($csv_file, "r")) !== FALSE) {
  fgetcsv($handle);   
  while (($data = fgetcsv($handle, 10000, ",")) !== 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];
  $col6 = $col[5];
  $col7 = $col[6];
  $col8 = $col[7];
  $col9 = $col[8];
  $col10 = $col[9];
  $col11 = $col[10];

// SQL Query to insert data into DataBase
 $query = "INSERT INTO csvtbl(sl_no,id,poke_no,star,p_name,cp,iv,primary1,secondary,candy,level) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."')";
$s     = mysql_query($query, $connect );
}
fclose($handle);
 }

 echo "Account added successfully imported to database!!<br>";

 //1 column entry query for another table
 $query1 = "INSERT INTO account(id) VALUES('".$col1."')";
$a     = mysql_query($query1, $connect );

echo "New Account added successfully imported to database!!";

mysql_close($connect);

} while ($filename <= 1000);
?>

0 个答案:

没有答案