在mysql脚本php中导入.csv

时间:2012-11-05 12:45:28

标签: php import

我有一个PHP脚本将文件导入我的mysql数据库。 但是当我尝试使用它时,我收到了这个错误:

找不到档案。确保指定了正确的路径

但我甚至没有选择一个文件,这是我的脚本:

<?php 
include ('db_connect.php');
//connect to the database

//

if ($_FILES[csv][size] > 0) {

    //get the csv file
    $file = $_FILES[csv][tmp_name];
    $handle = fopen($file,"r");

    //loop through the csv file and insert into database
    do {
        if ($data[0]) {
            mysql_query("INSERT INTO test (nummer, branche) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."',
                )
            ");
        }
    } while ($data = fgetcsv($handle,10000,",","'"));
    //

    //redirect
    header('Location: import.php?success=1'); die;

}

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import a CSV File with PHP & MySQL</title>
</head>

<body>

<?php if (!empty($_GET[success])) { echo "<b>Your file has been imported.</b><br><br>"; } //generic success notice ?>

<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
  Choose your file: <br />
  <input name="csv" type="file" id="csv" />
  <input type="submit" name="Submit" value="Submit" />
</form>

</body>
</html>

任何人都可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

关于do / while循环的评论:不,我的意思是这样的

$handle = fopen($file,"r");
if ($handle !== FALSE) {
    while (!feof($handle)) {
        $data = fgetcsv($handle,10000,",","'");
        if ($data[0]) {
            mysql_query("INSERT INTO test (nummer, branche) VALUES
                (
                    '".addslashes($data[0])."',
                    '".addslashes($data[1])."'
                )
            ");
        }

    }
    fclose($handle);
}