php将csv文件导入到mysql数据库的方法_php技巧
程序员文章站
2022-03-21 22:55:12
...
本文实例讲述了php将csv文件导入到mysql数据库的方法。分享给大家供大家参考。具体分析如下:
$fname = $_files['myfile']['name'];
$do = copy($_files['myfile']['tmp_name'],$fname);
if ($do){
echo"导入数据成功
";
}else{
echo "";
}
error_reporting(0);// 导入csv格式的文件
$connect=mysql_connect("localhost","root","") or die("could not connect to database");
mysql_select_db("gklqtzcx",$connect) or die (mysql_error());
mysql_query("set names 'gbk'");
$fname = $_files['myfile']['name'];
$handle=fopen("$fname","r");
while($data=fgetcsv($handle,10000,",")){
$q="insert into records (name,classes,a_time,college,notify,receiver,r_time,handler) values ('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";
mysql_query($q) or die (mysql_error());
}
fclose($handle);
echo "1秒钟转入列表页,请稍等.";
?>
本程序实现数据导入原理是先把csv文件上传到服务器,然后再通过php的fopen与fgetcsv文件把数据保存到数组,然后再用while把数据一条条插入到mysql数据库,代码如下:
复制代码 代码如下:
$fname = $_files['myfile']['name'];
$do = copy($_files['myfile']['tmp_name'],$fname);
if ($do){
echo"导入数据成功
";
}else{
echo "";
}
error_reporting(0);// 导入csv格式的文件
$connect=mysql_connect("localhost","root","") or die("could not connect to database");
mysql_select_db("gklqtzcx",$connect) or die (mysql_error());
mysql_query("set names 'gbk'");
$fname = $_files['myfile']['name'];
$handle=fopen("$fname","r");
while($data=fgetcsv($handle,10000,",")){
$q="insert into records (name,classes,a_time,college,notify,receiver,r_time,handler) values ('$data[1]','$data[2]','$data[3]','$data[4]','$data[5]','$data[6]','$data[7]','$data[8]')";
mysql_query($q) or die (mysql_error());
}
fclose($handle);
echo "1秒钟转入列表页,请稍等.";
?>
希望本文所述对大家的php程序设计有所帮助。
上一篇: 浅谈php数组如何实现冒泡排序算法
下一篇: PHP开发中常用的8个小技巧_php技巧