php将本地CSV文件导入MYSQL表

时间:2016-10-10 02:10:10

标签: php mysql

我发现这段代码可以将我PC上的本地CSV文件导入到MYSQL表中。我将此文件保存为 import.php

我在this

上找到了代码
  <?php

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

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

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

// path where your CSV file is located
define('CSV_PATH','C:\Users\Administrator\Desktop\Images\CSV');

// Name of your CSV file
$csv_file = CSV_PATH . "Booth_shares.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];
        }

 $date = $col[0];
 $filename = $col[1];
 $directory = $col[2];
 $type = $col[3];
 $to = $col[4];

// SQL Query to insert data into DataBase
$query = "INSERT INTO tblshops(date,filename,directory,type,to) VALUES('".$date."','".$filename."','".$directory."','".$type."','".$to."')";
$s     = mysql_query($query, $connect );
 }
    fclose($handle);
}

echo "File data successfully imported to database!!";
mysql_close($connect);
?>

当我导航到 example.com/import.php 时,它表示文件数据已成功导入数据库!! 但是当我登录MYSQL时,没有记录。

我验证CSV列名称是否与MYSQL字段名称匹配。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

我对你的评论中的所有内容仍然适用,但是,你的问题很可能就在这里:

define('CSV_PATH','C:\Users\Administrator\Desktop\Images\CSV');

最有可能的是你真正需要的是:

define('CSV_PATH','C:\Users\Administrator\Desktop\Images\CSV\');