【发布时间】:2014-07-30 06:30:47
【问题描述】:
所以我有一个 CSV 文件,我正试图将其制成表格。
在出现太多错误后,我放弃了导入 GUI,并尝试通过 php 文件完成导入。
//create table with KNOWN values
mysql_query("CREATE TABLE uri_faculty
(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
id INT(15),
lname VARCHAR(50),
fname VARCHAR(50),
mi VARCHAR(3),
Spc_Title VARCHAR(50),
title VARCHAR(50),
deptid INT(5),
dept VARCHAR(50),
degree1 VARCHAR(10),
earned1 INT(4),
school1 VARCHAR(75),
degree2 VARCHAR(10),
earned2 INT(4),
school2 VARCHAR(75),
degree3 VARCHAR(10),
earned3 INT(4),
school3 VARCHAR(75),
degree4 VARCHAR(10),
earned4 INT(4),
school4 VARCHAR(75),
degree5 VARCHAR(10),
earned5 INT(4),
school5 VARCHAR(75),
degree6 VARCHAR(10),
earned6 INT(4),
school6 VARCHAR(75)
)");
//Get CSV file
$getfile = 'faculty_delim2.csv';
$csvfopen = fopen($getfile, "r");
//loop to fill csvget with arrays
for($i=0;!feof($csvfopen);$i++){
$array = fgetcsv($csvfopen);
$insert = implode("','", $array);
//to exclude the first 2 lines (titles of document)
if($i>=1){
//values to be inserted into SQL are displayed
//echo var_dump($array[$i])." <br> ";
$sqlval = $insert;
// var_dump($sqlval);
//the while loop will constantly place values into the database until the file is finished
mysql_query("INSERT INTO uri_faculty (id,lname,fname,mi,Spc_Title,title,deptid,dept,
degree1,earned1,school1,
degree2,earned2,school2,
degree3,earned3,school3,
degree4,earned4,school4,
degree5,earned5,school5,
degree6,earned6,school6,) VALUES ('$sqlval')
");
}
}
fclose($csvfopen);
echo "complete";
?>
我不断收到一条错误消息,说 implode 接收到的参数不正确,但我发现的每一点文档都表明我是正确的。
我更改了文件的权限,它在正确的位置。
【问题讨论】:
-
for($i=0;!feof($csvfopen);$i++){应该做什么?为什么不使用简单的while(!feof($csvfopen)){ -
您要进行一次性导入?为什么不熟悉
LOAD DATA LOCAL INFILE?这确实是最好的方法,因为在 PHP 中您需要考虑所有的引用、转义等。 -
@user3678068,
','是他将数组内爆的分隔符,以便为查询构建字符串。 -
@Brobin。哎呀,我混合了内爆和爆炸......
-
var_dump($array)。你可能得到一个布尔值 false,这意味着 fgetcsv 失败。