How to import an excel file to a mysql database using php
This article mainly introduces how to import excel files from php to mysql databases, analyzes the skills of excel file operations in phpexcel and the methods for importing databases, which has some reference value, for more information, see
This example describes how to import an excel file from php to a mysql database. Share it with you for your reference. The specific analysis is as follows:
To import an excel file from php to the mysql database, we need to use a phpexcel file. With this file, we can quickly and easily import an excel file to the mysql database, here is an example to illustrate the specific usage.
Prepare a database before import. The SQL statement code is as follows:
The Code is as follows:
/*
Navicat MySQL Data Transfer
Source Server: localhost
Source Server Version: 50133
Source Host: localhost: 3306
Source Database: test
Target Server Type: MYSQL
Target Server versions: 50133
File Encoding: 65001
Date: 2011-10-11 14:11:38
*/
SET FOREIGN_KEY_CHECKS = 0;
------------------------------
-- Table structure for 'execl'
------------------------------
Drop table if exists 'execl ';
Create table 'execl '(
'Id' int (11) not null AUTO_INCREMENT,
'Name' varchar (20) default null,
Primary key ('id ')
) ENGINE = MyISAM AUTO_INCREMENT = 16 default charset = latin1;
------------------------------
-- Records of execl
------------------------------
Insert into 'execl' VALUES ('14', 'Jim ');
Insert into 'execl' VALUES ('15', 'taurus ');
Php processing program. here we need to use a phpexcel file, which can be searched and downloaded by Baidu. The Code is as follows:
The Code is as follows:
<? Php
If ($ _ FILES ['execl'] ['name']) {
$ Db = mysql_connect ('localhost', 'root ','');
Mysql_select_db ('test ');
Mysql_query ('set names gbk ');
Require_once 'reader. php ';
$ Data = new Spreadsheet_Excel_Reader ();
$ Data-> setOutputEncoding ('cp936 ');
$ Data-> read ($ _ FILES ['execl'] ['name']);
Error_reporting (E_ALL ^ E_NOTICE );
$ SQL = "";
For ($ I = 1; $ I <= $ data-> sheets [0] ['numrows ']; $ I ++)
{
If ($ data-> sheets [0] ['cells '] [$ I] [1]! = ""){
$ SQL = "INSERT INTO 'execl' ('name') values ('". $ data-> sheets [0] ['cells '] [$ I] [2]. "');";
If (mysql_query ($ SQL )){
Echo 'successfully ';
} Else {
Die ('failed ');
}
}
}
}
?>
<Head>
</Head>
<Body>
<Form action = "" method = "post" enctype = "multipart/form-data">
<Input type = "file" name = "execl"/>
<Input type = "submit" value = "import data"/>
</Form>
</Body>
I hope this article will help you with php programming.