PHP导入CSV到mysql数据库添加额外的空行

时间:2014-11-09 14:34:15

标签: php mysql csv

我创建了一个导入csv文件并将值输入mysql数据库的脚本。每次脚本运行它都有效,但随后它会在数据库中创建一个包含所有空白字段的额外条目。因此,如果csv文件有5行,那么它将输入6到mysql,第6个是空白。

//----------------------------------- Check File Upload -----------------------------------------------------------
if(isset($_POST["submit"])) {
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION);
// Check if image file is a actual image or fake image

        $uploadOk = 1;  

// Check if file already exists
if (file_exists($target_file)) {
    echo "Sorry, file already exists.";
    $uploadOk = 0;
}
// Check file size
if ($_FILES["fileToUpload"]["size"] > 5000000) {
    echo "Sorry, your file is too large.";
    $uploadOk = 0;
}

// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
    echo "Sorry, your file was not uploaded.";
// if everything is ok, try to upload file
} else {
    if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
        echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
    } else {
        echo "Sorry, there was an error uploading your file.";
    }
}


//---------------------------- import values ------------------------------------------------------------------------------------------
    $connect = mysql_connect($dbhost,$dbuser,$dbpass);
    if (!$connect) {
    die('Could not connect to MySQL: ' . mysql_error());
    }

    $cid =mysql_select_db($dbname,$connect);
    // supply your database name

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

    $csv_file = CSV_PATH . basename( $_FILES["fileToUpload"]["name"]); // Name of your CSV file
    $csvfile = fopen($csv_file, 'r');
    $theData = fgets($csvfile);
    $i = 0;
    while (!feof($csvfile)) {
    $csv_data[] = fgets($csvfile, 1024);
    $csv_array = explode(",", $csv_data[$i]);
    $insert_csv = array();
    $insert_csv['TerminalID'] = $csv_array[0];
    $insert_csv['Name'] = $csv_array[1];
    $insert_csv['Address'] = $csv_array[2];
    $query = "INSERT INTO tickets(termid,name,address)
    VALUES('".$insert_csv['TerminalID']."','".$insert_csv['Name']."','".$insert_csv['Address']."')";
    $n=mysql_query($query, $connect );
    $i++;
    }
    fclose($csvfile);

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

0 个答案:

没有答案