无法将CSV文件上传到数据库

时间:2014-04-24 13:50:07

标签: php mysql csv

我有一个上传页面,用户只能上传CSV文件。但是,当我点击上传按钮时,没有任何内容上传到我的数据库,也没有显示任何错误消息。只有返回按钮显示这意味着我的代码不能正确执行我的代码。我该如何解决这个问题?

    CREATE TABLE `Jobs` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `date` date NOT NULL,
  `order_ref` varchar(250) NOT NULL,
  `first_name` varchar(250) NOT NULL,
  `last_name` varchar(250) NOT NULL,
  `postcode` varchar(250) NOT NULL,
  `country` varchar(250) NOT NULL,
  `quantity` varchar(250) NOT NULL,
  `scott_packing` varchar(250) NOT NULL,
  `packing_price` varchar(250) NOT NULL,
  `courier_price` varchar(250) NOT NULL,
  `dispatch_type` varchar(250) NOT NULL DEFAULT '',
  `tracking_number` varchar(250) NOT NULL,
  `job_status` varchar(250) NOT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
)

HTML:

    <?
session_start();
if(!session_is_registered(myusername))
{
    header("location:../index.php");
}
?>
<?
include("../template/header.php");
?>
<!DOCTYPE html>
<head>
    <title></title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
</head>
<body>
    <div class="content">
        <div class="toggle">
            <div class="header"><img style="float: right; padding: 10px;" src="../img/show.gif"><h4>Upload New File:</h4></div>  
    <form id="upload" action="upload_file.php" method="post" enctype="multipart/form-data">
        <input type="file" name="uploaded_file"><br>
        <input type="submit" value="Upload file">
    </form>
    <!--<p>
        <a href="list_files.php" style="padding: 20px;">See all files</a>
    </p>-->
</div>
</div>
</body>
</html>

upload_file.php:

    <?php


if(isset($_FILES['uploaded_file'])) {
    if($_FILES['uploaded_file']['error'] == 0) {

        $database = "spineless";

        $dblink = mysql_connect("localhost", "root", "vario007")
           or die("Could not connect");

        $db = mysql_select_db($database)
        or die("Could not select database");

        if(mysql_errno()) {
            die("MySQL connection failed: ". mysql_error());
        }

        $file = $_FILES  ['uploaded_file']['tmp_name'];
        $handle = fopen($file, "r");
        $row = 1;
        while (($data = fgetcsv($handle, 0, ",","'")) !== FALSE)
        {
            if($row == 1)
            {
                // skip the first row   
            }
            else
            {
                //csv format data like this 
                //$row[0] = date
                //$row[1] = order_ref
                //$row[2] = postcode
                //$row[3] = country
                //$row[4] = quantity
                //$row[5] = packing_price
                //$row[6] = dispatch_type

                $query = "
                INSERT INTO `Jobs` (
                `date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
                )
                VALUES (
                '".$data[0]."', '".$data[1]."', '".$data[2]."', '".$data[3]."', '".$data[4]."', '".$data[5]."', '".$data[6]."', NOW()
                )";
                $result = mysql_query($query);


                 // Check if it was successfull
                if(!$result) {
                    echo 'Success! Your file was successfully added!';
                }
                else {
                    echo 'Error! Failed to insert the file';

                 }
            }
            $row++;
        }



    }
    else {
        echo 'An error accured while the file was being uploaded. '
           . 'Error code: '. intval($_FILES['uploaded_file']['error']);
    }

    // Close the mysql connection
    mysql_close();
}
else {
    echo 'Error! A file was not sent!';
}

// Echo a link back to the main page
echo '<p>Click <a href="joblist.php">here</a> to go back</p>';
?>

这就是CSV的样子: http://i754.photobucket.com/albums/xx182/rache_R/Screenshot2014-04-24at151348_zps807cedb0.png

3 个答案:

答案 0 :(得分:1)

所以我设法解决了自己的问题。在查看我的代码之后,我注意到我的代码在while循环之前已经很好了。在读取文件时,PHP无法正确识别行结尾,因此启用auto_detect_line_endings运行时配置有助于解决我的问题。请注意,auto_detect_line_endings设置在 fopen之前,而不是之后。

    <?php

if(isset($_FILES['uploaded_file'])) {


    if($_FILES['uploaded_file']['error'] == 0) {

        // Connect to database
        $database = "spineless";
        $link = mysql_connect("localhost", "root", "vario007") or die("Could not connect");
        $db = mysql_select_db($database,$link) or die("Could not select database");

        // Upload file
        $file = $_FILES['uploaded_file']['tmp_name'];
        ini_set("auto_detect_line_endings", true); // auto_detect_line_endings added here
        $handle = fopen($file, "r");
        $row = 1;
        while (($data = fgetcsv($handle, 0, ",","'")) !== FALSE)
        {
            if($row == 1)
            {
                // skip the first row   
            }
            else
            {
                //csv format data like this 
                //$row[0] = date
                //$row[1] = order_ref
                //$row[2] = postcode
                //$row[3] = country
                //$row[4] = quantity
                //$row[5] = packing_price
                //$row[6] = dispatch_type

                $query = "
                INSERT INTO `Jobs` (
                `date`, `order_ref`, `postcode`, `country`, `quantity`, `packing_price`, `dispatch_type`, `created`
                )
                VALUES (
                '".$data[1]."', '".$data[2]."', '".$data[5]."', '".$data[6]."', '".$data[7]."', '".$data[9]."', '".$data[11]."', NOW()
                )";

                $result = mysql_query($query);




                 // Check if it was successfull
                if($result) {
                    echo 'Success! Your file was successfully added!';
                }
                else {
                    echo 'Error! Failed to insert the file';

                 }
            }
            $row++;
        }

    }
    else {
        echo 'An error accured while the file was being uploaded. ';
    }

    // Close the mysql connection
    mysql_close();
}
else {
    echo 'Error! A file was not sent!';
} 

// Echo a link back to the main page
echo '<p>Click <a href="joblist.php">here</a> to go back</p>';
?>

答案 1 :(得分:0)

好的,我根据您的信息设置了一个数据库,并使用您提供的数据创建了一个CSV文件。好消息是你的代码对我来说非常好(对我而言),但对于两个小问题。

您的成功消息是错误的,请删除!

if($result){
echo 'Success! Your file was successfully added!';
}else{
echo 'Error! Failed to insert the file';
}

您还尝试将日期字符串03/02/2014插入DATE数据类型。这不会起作用,您需要相应地格式化此字符串。作为临时措施,我只是将DB中的数据类型更改为VARCHAR(20)。

修复了这两件小事:

enter image description here

答案 2 :(得分:0)

    <?
session_start();

在输出发送到浏览器之后,您无法启动会话,在这种情况下,会有一些空白空间。

调整此项,最好不要使用任何类型的short_open_tags

<?php
session_start();