Import csv files from php to mysql database
2. run insertdb. php on the page.
Session_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 ("./conn. 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 student (typeId, name, sex, age) value ($ arr_result [0], '$ name',' $ sex ', $ arr_result [3]) ";
- // Echo $ SQL;
- Mysql_query ("set names utf8 ");
- $ Result = mysql_query ($ SQL );
- If ($ result ){
- Echo "inserted successfully !!! ";
- } Else {
- Echo "insertion failed !!! ";
- }
- }
- $ Row ++;
- }
- Fclose ($ handle );
- ?>
|