Home >php教程 >php手册 >php把csv文件导入到mysql数据库

php把csv文件导入到mysql数据库

WBOY
WBOYOriginal
2016-05-24 18:30:54932browse

本程序实现数据导入原理是先把csv文件上传到服务器,然后再通过php的fopen与fgetcsv文件把数据保存到数组,然后再用while把数据一条条插入到mysql数据库,代码如下:

<?php
$fname = $_files[&#39;myfile&#39;][&#39;name&#39;];
$do = copy($_files[&#39;myfile&#39;][&#39;tmp_name&#39;], $fname);
if ($do) {
    echo "导入数据成功<br>";
} 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 &#39;gbk&#39;");
$fname = $_files[&#39;myfile&#39;][&#39;name&#39;];
$handle = fopen("$fname", "r");
while ($data = fgetcsv($handle, 10000, ",")) {
    $q = "insert into records (name,classes,a_time,college,notify,receiver,r_time,handler) values (&#39;$data[1]&#39;,&#39;$data[2]&#39;,&#39;$data[3]&#39;,&#39;$data[4]&#39;,&#39;$data[5]&#39;,&#39;$data[6]&#39;,&#39;$data[7]&#39;,&#39;$data[8]&#39;)";
    mysql_query($q) or die(mysql_error());
}
fclose($handle);
echo "<meta http-equiv=\"refresh\" content=\"1;url=list.php\">1秒钟转入列表页,请稍等." 
?>
<form enctype="multipart/form-data" action="<?php echo"".$_server["php_self"].""; ?>" method="post"> 
<p>导入cvs数据 <input name="myfile" type="file"> <input value="提交" type="submit"> 
</p> 
</form>


永久链接:

转载随意!带上文章地址吧。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn