简体   繁体   English

LOAD DATA INFILE不会将CSV数据上传到MySQL表中,没有错误

[英]LOAD DATA INFILE doesn't upload CSV data into MySQL table with no error

Update: 更新:

I attempted to execute the query generated by PHP script in phpMyAdmin's SQL tab and got: 我试图在phpMyAdmin的SQL选项卡中执行由PHP脚本生成的查询,并得到:

#7890 - Can't find file 'C:wamp    mpphpB4C4.tmp'.

It cut path between C:wamp and tmp file name. 它剪切了C:wamp和tmp文件名之间的路径。 Could it be I'm escaping file path incorrectly?: $file = $_FILES['csv']['tmp_name']; 是否可能是我错误地转义了文件路径?: $file = $_FILES['csv']['tmp_name'];


I'm writing this cool webapp using PHP and MySQL. 我正在使用PHP和MySQL编写这个很酷的web应用程序。 One of its functions is to upload contents of a CSV file into a table in my database called suites. 它的功能之一是将CSV文件的内容上载到数据库中称为套件的表中。

CSV file looks like this: CSV文件如下所示:

1230,Cool Business,,1
3612,Not-so-cool Business Ltd.,John Smith,0

Column meanings from left to right in this CSV go as such: Suite number, Name of the business operating at this suite, Primary contact(optional), Did I already go there?(0 - no, 1 - yes; optional also). 在此CSV中从左到右的列含义是:套件号,在此套件下运营的公司名称,主要联系人(可选),我是否已经去过那里?(0-否,1-是;也是可选的)。

The database table, named suites, has the following structure: 数据库表名为套件,具有以下结构:

suite_id (primary), location_id (foreign referencing locations table), suite , business , contact , visited suite_id (主要), location_id (外部参照位置表), suite业务联系人 ,已访问

As you may have already guessed by now I'm trying to insert only the last 4 columns of the suites table with the above CSV example. 正如您可能已经猜到的那样,我正在尝试仅使用上述CSV示例插入套件表的最后4列。

I attempt to do that with the following PHP code: 我尝试使用以下PHP代码来做到这一点:

<?php

/**
 * Class registration
 * handles the user registration
 */
class SuiteCSV
{
    /**
     * @var object $db_connection The database connection
     */
    private $db_connection = null;
    /**
     * @var array $errors Collection of error messages
     */
    public $errors = array();
    /**
     * @var array $messages Collection of success / neutral messages
     */
    public $messages = array();

    /**
     * the function "__construct()" automatically starts whenever an object of this class is created,
     * you know, when you do "$registration = new Registration();"
     */
    public function __construct()
    {
        if(isset($_POST["add_suite_csv"])){
            $this->addSuiteCSV();
        }
    }

    /**
     * handles the entire registration process. checks all error possibilities
     * and creates a new user in the database if everything is fine
     */ 
    private function addSuiteCSV()
    {
        if (empty($_POST['suite_location_csv'])) {
            $this->errors[] = "Must select location of suite";
        }else{

        // create a database connection
        $this->db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

        if (!$this->db_connection->set_charset("utf8")) {
                $this->errors[] = $this->db_connection->error;
        }

        if (!$this->db_connection->connect_errno) {
            $suite_location_csv = $this->db_connection->real_escape_string(strip_tags($_POST['suite_location_csv'], ENT_QUOTES));
            if ($_FILES['csv']['size'] > 0) {
                $file = $_FILES['csv']['tmp_name'];
                $query = <<<eof
LOAD DATA INFILE '$file'
INTO TABLE sales.suites
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\r\n'
(suite,business,contact,visited)
SET location_id = $suite_location_csv
eof;

                $query_add_suite_csv = $this->db_connection->query($query);

                if ($query_add_suite_csv) {
                    $this->messages[] = "CSV has been uploaded.";
                } else {
                    $this->errors[] = "Sorry, I couldn't upload this CSV. Try again.";
                }

                var_dump($query_add_suite_csv);


            }else{
                $this->errors[] = "Must select CSV file for upload";
            }
        }else{
            $this->errors[] = "Database connection error";
        }
    }
}
}

$suite_location in this case is a value that user will select from a drop down menu on the upload form, which in turn is populated with another PHP script when page is loaded. 在这种情况下, $ suite_location是用户将从上载表单的下拉菜单中选择的值,当加载页面时,该菜单将依次填充另一个PHP脚本。 Values of $suite_location are location_id values in locations table which has a foreign key in suite table. $ suite_location的值是locations表中的location_id值,其中suite表中具有外键。

So, the user picks a location, selects a CSV file and uploads it to the suites table. 因此,用户选择一个位置,选择一个CSV文件并将其上传到套件表。

Nothing is happening though. 不过什么也没发生。 There are no errors. 没有错误。 I've looked at LOAD DATA INFILE documentation and tried to apply what I've understood from it, but still doesn't seem to work. 查看了LOAD DATA INFILE文档,并尝试应用我从中了解的内容,但似乎仍然行不通。

Form snippet: 表单摘要:

<form class="form-horizontal" method="post" action="admin_add_location.php" enctype="multipart/form-data" name="addsuitecsv">
    <div class="form-group">
        <label class="control-label">Select Locations:</label>
        <div class="">
            <select size="6" name="suite_location_csv">
                    <?php $location->getLocations(); ?>
            </select>
        </div>
        <label class="control-label">Choose your file:</label>
        <div class="">
            <input name="csv" type="file" id="csv" />
        </div>
        <button class="btn btn_success" name="add_suite_csv" type="submit"><span class="glyphicon glyphicon-upload" ></span>Import CSV</button>
    </div>
</form>

Add View PHP: 添加查看PHP:

<?php
    // include the configs / constants for the database connection
    require_once("config/db.php");

    // load the login class
    require_once("classes/Login.php");

    // create a login object. when this object is created, it will do all login/logout stuff automatically
    // so this single line handles the entire login process. in consequence, you can simply ...
    $login = new Login();

    // only administrators can see
    if ($login->isUserLoggedIn() == true && $_SESSION['user_group'] == 0) {
        require_once("classes/Location.php");
        $location = new location();
        require_once("classes/Suite.php");
        $suite = new Suite();
        require_once("classes/SuiteCSV.php");
        $suitecsv = new SuiteCSV();
        include("includes/header.php");
        include("views/admin_add_location_view.php");
        include("views/admin_add_suite_view.php");
        include("views/admin_add_suite_csv_view.php");
        include("includes/footer.php");
    }else{
        echo "<h1>Access denied</h1>";
        include("views/go_back_view.php");
    }
?>

Changing: 更改:

$file = $_FILES['csv']['tmp_name'];

to: 至:

$file = addslashes($_FILES['csv']['tmp_name']);

fixed the issue and CSV now gets uploaded. 解决了该问题,现在可以上传CSV。

Basically I had to escape slashes in the file path. 基本上,我必须在文件路径中转义斜线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM