This article mainly introduces the PHP programming implementation of the CSV file import MySQL database method, involving PHP file reading, conversion, database connection, insert and other related operations skills, the need for friends can refer to the next
Specific as follows:
config.db.php content is as follows;
<?php$username= "root"; $userpass = "123"; $dbhost = "localhost"; $dbdatabase = "credits2stakes";//Generate a connection $db_connect= Mysql_connect ($dbhost, $username, $userpass) or die ("Unable to connect to the mysql!"); /Select a database to operate on mysql_select_db ($dbdatabase, $db _connect);
index.php content is as follows:
<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "/><form name=" Frm1 "enctype=" Multipart/form-data "action=" insertdb.php "method=" POST "> <input name= "filename" type= "file"/><input name= "Submit" type= "Submit" value= "Import"/></form>
insertdb.php content is as follows:
<?phpsession_start (); Header ("Content-type:text/html;charset:utf-8");//global variable $file=$_files[' filename ']; $max _ Size= "2000000"; Maximum file limit (in bytes) $fname = $file [' name ']; $ftype =strtolower (substr (STRRCHR ($fname, '. '), 1));//file Format $uploadfile= $file [' Tmp_name '];if ($_server[' request_method ']== ' POST ') {if (Is_uploaded_file ($uploadfile)) {if ($file [' Size ']> $max _size) {echo "Import file is too large"; Exit } if ($ftype! = ' csv ') {echo "Import file type is error"; Exit }}else{echo "The file is not empty!"; Exit }}require ("./config.db.php"); Connect MySQL database $row=0; $filename = $file [' Tmp_name ']; $handle =fopen ($filename, ' R '); while (!feof ($handle) && $ Data=fgetcsv ($handle, +, ', ')) {$arr _result=array (); if ($row ==0) {$row + +; Continue } if ($row >0 &&!empty ($data)) {$num =count ($data); for ($i =0; $i < $num; $i + +) {Array_push ($arr _result, $data [$i]); }//$name = Iconv (' gb2312 ', ' utf-8 ', $arr _result[1]); $sex = Iconv (' gb2312 ', ' Utf-8 ', $arr _RESULT[2]); $sql = "INSERT into Inviter (inviter,invitees,time) value ($arr _result[1], $arr _result[2], $arr _result[3])"; Echo $sql; mysql_query ("Set names UTF8"); $result =mysql_query ($sql); if ($result) {echo "Insert succeeded!!! "; }else{echo "insertion failure!!! "; }} $row + +;} Fclose ($handle);? >
The above is the whole content of this article, I hope that everyone's study has helped.