PHP programming to import csv files into the mysql database,
This article describes how to import csv files into mysql databases through PHP programming. We will share this with you for your reference. The details are as follows:
The content of config. db. php 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 the database mysql_select_db ($ dbdatabase, $ db_connect) to be operated );
The 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>
The content of insertdb. php is as follows:
<? Phpsession_start (); header ("Content-type: text/html; charset: UTF-8"); // global variable $ file = $ _ FILES ['filename']; $ max_size = "2000000"; // maximum file size (unit: byte) $ 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 to the mysql database $ row = 0; $ filename = $ file ['tmp _ name']; $ handle = fopen ($ filename, 'R '); while (! Feof ($ handle) & $ data = fgetcsv ($ handle, 1000, ',') {$ 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 successful !!! ";}Else {echo" insertion failed !!! ";}}$ Row ++;} fclose ($ handle);?>