我试过的代码是
$source = fopen('filename.csv', 'r') or die("Problem open file");
while (($data = fgetcsv($source, 1000, ",")) !== FALSE)
{
$name = $data[0];
`$mobile = $data[1];
mysql_query("INSERT INTO `table` (`name`,`mobile`) VALUES ('".$name."','".$mobile ."') ");
}
fclose($source);
但它只需要最后一次记录......
答案 0 :(得分:0)
使用PHP fgetcsv()
和mysqli()
,这是一种简单的方法:
<强> 1。连接到mysqli:
$mysqli = new mysqli("localhost", "my_user", "my_password", "my_db");
<强> 2。打开CSV文件:
$source = fopen('filename.csv', 'r') or die("Problem open file");
第3。使用循环读取CSV并将插入查询放在变量中:
$query="";
do {
if ($fields[0]) {
$query.="INSERT INTO `table_name` (`name`, `mobile`) VALUES
(
'".addslashes($fields[0])."',
'".addslashes($fields[1])."'
)
;";
}
} while ($fields = fgetcsv($source,1000,",","'"));
<强> 4。执行您的查询并关闭mysqli:
if($mysqli->multi_query($query)) echo "Data successfuly added";
$mysqli->close();
答案 1 :(得分:0)
为什么不使用MySQL添加整个文件而不是按行分解?像
这样的东西LOAD DATA INFILE 'filename.csv' INTO TABLE table FIELDS TERMINATED BY ',';
或者如果您有特定的列需要进入特定字段,
LOAD DATA INFILE 'filename.csv' INTO TABLE table FIELDS TERMINATED BY ',' (@c1, @c2)
set name = @c1, mobile = @c2;