将csv文件上传到Mysql / PHP文件

时间:2014-06-20 22:24:47

标签: php mysql file csv upload

//connect to Database

mysql_select_db($database_csv, $csv);

if (isset($_POST['submit'])) {

if (is_uploaded_file($_FILES['filename']['tmp_name'])) {

echo "<br><center><p>" . " ". $_FILES['filename']['name'] ." " . "</p></center>";
                                                        }

//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
$firstRow = true;
$count = 0; //skip first line of the CSV file 
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {

if($count) //skip first line of the CSV file 
{

$name=$data[0];

$description=$data[1];

$price=$data[2];

$shipping=$data[3];

$quantity=$data[4];

$import="INSERT into results (name,description,price,shipping,quantity) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";

mysql_query($import) or die(mysql_error());
}
$count++;
}

fclose($handle);

?>

使用PHP / Mysql中的FileUpload上传.CSV文件,但csv中的数据全部插入五列中的一列,请阅读我的代码和帮助。 在此先感谢..

2 个答案:

答案 0 :(得分:2)

简单的LOAD DATA INFILE可以正常工作。它也会快得多。

<强>代码:

<?php
//connect to Database
mysql_select_db($database_csv, $csv);

if (isset($_POST['submit'])) {

    $tmp = $_FILES['filename']['tmp_name'];
    $name = $_FILES['filename']['name'];

    //Can be any full path, just don't end with a /. That will be added in in the path variable
    $uploads_dir = 'C:/Users/Ernest/Desktop';

    $path = $uploads_dir.'/'.$name;

    if(move_uploaded_file($tmp, $path)){
        echo "<br><center><p>". $name ."</p></center>";

        //Import uploaded file to Database
        //If the query fails, try LOAD DATA LOCAL INFILE
        $import = "
        LOAD DATA INFILE '".$path."'
               INTO TABLE results  CHARACTER SET utf8 FIELDS TERMINATED BY ','
               OPTIONALLY ENCLOSED BY '\"' IGNORE 1 LINES (name, description, price, shipping, quantity);
        ";

        mysql_query($import) or die(mysql_error());
        //If you do not want to keep the csv, you can delete it after this point.
        //unlink($path);

    }else{
        echo 'Failed to move uploaded files';
    }

}
?>

答案 1 :(得分:0)

试试这个:

if($count) //skip first line of the CSV file 
{

$data[0]=$data[0];

$data[1]=$data[1];

$data[2]=$data[2];

$data[3]=$data[3];

$data[4]=$data[4];

$import="INSERT into results (name,description,price,shipping,quantity) VALUES('$data[0]','$data[1]','$data[2]','$data[3]','$data[4]')";

mysql_query($import) or die(mysql_error());
}
$count++;
}