本文執行個體講述了php將csv檔案匯入到mysql資料庫的方法。分享給大家供大家參考。具體分析如下:
本程式實現資料匯入原理是先把csv檔案上傳到伺服器,然後再通過php的fopen與fgetcsv檔案把資料儲存到數組,然後再用while把資料一條條插入到mysql資料庫,代碼如下:
複製代碼 代碼如下:
<?php
$fname = $_files['myfile']['name'];
$do = copy($_files['myfile']['tmp_name'],$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 '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 "<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>
希望本文所述對大家的php程式設計有所協助。