【发布时间】:2014-12-27 11:21:00
【问题描述】:
我想将 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;
}
}
?>
=> The trip insert failed
我很确定问题来自\ 或我无法定位的任何其他角色。
谢谢你的帮助。
【问题讨论】:
-
你确定你有 \n 作为换行符吗?试试\r\n
-
检查它在你得到这个错误后查询会加载文件。
-
如果您想传递反斜杠和“n”而不是换行符,您可能必须转义
\n。 -
为什么要混用mysql和mysqli函数???仔细检查
标签: php mysql load-data-infile