Many new users are confused about how to use php-excel-reader to read excel content and store it in the database. This article will introduce detailed solutions, for more information, see the previous article about how to use php-excel-reader to read excel files:
Create a database table as follows:
-- Database: 'alumni'
-- Table structure 'alumni'
Create table if not exists 'alumni '(
'Id' bigint (20) not null AUTO_INCREMENT,
'Gid' varchar (20) default null comment 'file number ',
'Student _ no' varchar (20) default null comment 'student ID ',
'Name' varchar (32) default null,
Primary key ('id '),
KEY 'gid' ('gid '),
KEY 'name' ('name ')
) ENGINE = MyISAM default charset = utf8;
The database results after import are as follows:
The php source code is as follows:
The Code is as follows:
Header ("Content-Type: text/html; charset = UTF-8 ");
Require_once 'excel _ reader2.php ';
Set_time_limit (20000 );
Ini_set ("memory_limit", "2000 M ");
// Use pdo to connect to the database
$ Dsn = "mysql: host = localhost; dbname = alumni ;";
$ User = "root ";
$ Password = "";
Try {
$ Dbh = new PDO ($ dsn, $ user, $ password );
$ Dbh-> query ('set names utf8 ;');
} Catch (PDOException $ e ){
Echo "connection failed". $ e-> getMessage ();
}
// Parameter binding operation for pdo
$ Stmt = $ dbh-> prepare ("insert into alumni (gid, student_no, name) values (: gid,: student_no,: name )");
$ Stmt-> bindParam (": gid", $ gid, PDO: PARAM_STR );
$ Stmt-> bindParam (": student_no", $ student_no, PDO: PARAM_STR );
$ Stmt-> bindParam (": name", $ name, PDO: PARAM_STR );
// Use php-excel-reader to read excel content
$ Data = new Spreadsheet_Excel_Reader ();
$ Data-> setOutputEncoding ('utf-8 ');
$ Data-> read ("stu.xls ");
For ($ I = 1; $ I <= $ data-> sheets [0] ['numrows ']; $ I ++ ){
For ($ j = 1; $ j <= 3; $ j ++ ){
$ Student_no = $ data-> sheets [0] ['cells '] [$ I] [1];
$ Name = $ data-> sheets [0] ['cells '] [$ I] [2];
$ Gid = $ data-> sheets [0] ['cells '] [$ I] [3];
}
// Insert the obtained excel content to the database
$ Stmt-> execute ();
}
Echo "execution successful ";
Echo "Last inserted ID:". $ dbh-> lastInsertId ();
?>
Considering that the excel volume is large, the PDO binding operation is used!