代码如下:
$conn=mysqli_connect("localhost","user","password","dbname");
//csv自动导入mysql,表头一致(csv保存为utf8),指定csv文件路径,数据表名称
//如:csv2mysql("/home/test/test.csv","testTB");
function csv2mysql($csv,$sqltable){
global $conn;
//注意文件要保存为utf8的csv格式
if ($csv==""){
return "csvERR:".$csv;
exit();
}
$csvArr=read_csv($csv);
$csvLine=count($csvArr);//csv文件行数
$colN=count($csvArr[1]);//字段数
//获取表头-第1行
$colTitle="";
for ($i=0;$i<$colN;$i++){
$colTitle.=$csvArr[1][$i];
if ($i<$colN-1){
$colTitle.=",";
}
}
$colTitle=trim($colTitle, "\xef\xbb\xbf\xff\xfe");//这行用于解决csv第一行多出的隐藏字符
//echo "ss".$colTitle;
//遍历每行数据插入数据表
$erri=0;
for ($L=2;$L<=$csvLine;$L++){
$Vsql="";
for ($i=0;$i<$colN;$i++){
$Vsql.="'".$csvArr[$L][$i]."'";
if ($i<$colN-1){
$Vsql.=",";
}
}
$Vsql=str_replace("'null'", "'NONE'", $Vsql);
$sqls="insert into $sqltable (".$colTitle.") value (".$Vsql.")";
$dosql=mysqli_query($conn,$sqls);
//注意在数据表中做索引,避免重复导入;
//echo $sqls."<br>";
if(!$dosql){
return "ERR:".$Vsql."<br>";
$erri++;
}
}
return("尝试导入".($csvLine-1)."条纪录,成功".($csvLine-1-$erri)."条,失败".$erri."条;<br><script src='../js/link.js'></script>");
}
//关闭数据库;
mysqli_close($conn);