php中的LOAD DATA INFILE错误

时间:2014-12-26 11:09:09

标签: php mysql load-data-infile

我想将csv文件内容导入到数据库表中,我使用此代码在phpmyadmin控制台中粘贴它时完全

LOAD DATA LOCAL INFILE '/Applications/MAMP/htdocs/testApp/trips.csv' INTO TABLE trips FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 ROWS (type,startDate,endDate,steps,coordinates,distance)

然而,当在php文件中使用它时,我有一个错误:

<?php

$host       = "localhost"; //Your database host server
$db         = "dbTest"; //Your database name
$user       = "root"; //Your database user
$pass       = "root"; //Your password
$connection = mysqli_connect($host, $user, $pass);

//Check to see if we can connect to the server
if (!$connection) {
    die("Database server connection failed.");
    die(mysqli_error($db));
} else {
    //Attempt to select the database
    $dbconnect = mysqli_select_db($connection, $db);
    //Check to see if we could select the database
    if (!$dbconnect) {
        die("Unable to connect to the specified database!");
    } else {
        $sql = "LOAD DATA LOCAL INFILE '/Applications/MAMP/htdocs/testApp/trips.csv' 
                INTO TABLE trips
                FIELDS TERMINATED BY ',' 
                LINES TERMINATED BY '\\n' 
               IGNORE 1 ROWS (type,startDate,endDate,steps,coordinates,distance)"
                ;

        $result = mysql_query($sql, $connection);

        if (mysql_affected_rows() == 1) {
            $message = "The trip was successfully inserted!";
        } else {
            $message = "The trip insert failed";
            $message .= mysql_error();
        }

        echo $message;
    }
}
?>

=&GT; The trip insert failed

我很确定问题来自\或我无法定位的任何其他角色。 谢谢你的帮助。

3 个答案:

答案 0 :(得分:2)

你混淆了MySQL和MySQLi插件 - 你正试图与MySQLi连接然后用MySQL执行查询。 你不能这样做。选择一个 API并一致地使用它。

所以:

mysql_query($sql)     ---> $connection->query($sql)
mysql_affected_rows() ---> $result->affected_rows()
mysql_error()         ---> $connection->error

最终,这与LOAD DATA INFILE无关,您应该尝试使用基本的SELECT!我建议阅读文档以了解您使用的功能。

答案 1 :(得分:1)

编辑:你在同一个脚本中混合了两个插件MYSQL和MYSQLi,下面我使用mysqli插件转储你代码的剩余部分,因为你的上半部分使用了mysqli ...

N.B :你不能这样做。选择任何一个API。

    $result = mysqli_query($connection, $sql);

    if (mysqli_affected_rows($connection) >= 1) {
        $message = "The trip was successfully inserted!";
    } else {
        $message = "The trip insert failed";
        $message .= mysqli_error($connection);
    }

答案 2 :(得分:-1)

尝试将trip.csv文件移至datadir - 您可以使用以下命令找到它:SELECT @ @datadir