如何使用php将excel文件导入mySQL数据库

时间:2015-02-11 06:18:30

标签: excel import

我想使用php将excel中的数据导入mySQL数据库。我尝试过使用其他问题中解释的方式,但没有对我有用。请告诉我如何使用php将数据导入数据库。

另外,请告诉我将要上传的Excel文件放在哪里,我的意思是系统中的位置。

2 个答案:

答案 0 :(得分:0)

方法1.您可以使用加载数据命令

http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html

方法2. Excel阅读器

https://code.google.com/p/php-excel-reader/

方法3. parseCSV

https://github.com/parsecsv/parsecsv-for-php

方法4。 (PHP 4,PHP 5)fgetcsv

 http://in1.php.net/fgetcsv

答案 1 :(得分:0)

请参阅此PHP代码

<?php

 //table Name
$tableName = "MyTable";
//database name
$dbName = "MyDatabase";


 $conn = mysql_connect("localhost", "root", "") or die(mysql_error());
 mysql_select_db($dbName) or die(mysql_error());

//get the first row fields
$fields = "";
$fieldsInsert = "";
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        $fieldsInsert .= '(';
        for ($c=0; $c < $num; $c++) {
            $fieldsInsert .=($c==0) ? '' : ', ';
            $fieldsInsert .="`".$data[$c]."`";
            $fields .="`".$data[$c]."` varchar(500) DEFAULT NULL,";
        }

        $fieldsInsert .= ')';
    }


    //drop table if exist
    if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))>=1) {
      mysql_query('DROP TABLE IF EXISTS `'.$tableName.'`') or die(mysql_error());
    }

    //create table
    $sql = "CREATE TABLE `".$tableName."` (
              `".$tableName."Id` int(100) unsigned NOT NULL AUTO_INCREMENT,
              ".$fields."
              PRIMARY KEY (`".$tableName."Id`)
            ) ";

    $retval = mysql_query( $sql, $conn );

    if(! $retval )
    {
      die('Could not create table: ' . mysql_error());
    }
    else {
        while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

                $num = count($data);
                $fieldsInsertvalues="";
                //get field values of each row
                for ($c=0; $c < $num; $c++) {
                    $fieldsInsertvalues .=($c==0) ? '(' : ', ';
                    $fieldsInsertvalues .="'".$data[$c]."'";
                }
                $fieldsInsertvalues .= ')';
                //insert the values to table
                $sql = "INSERT INTO ".$tableName." ".$fieldsInsert."  VALUES  ".$fieldsInsertvalues;
                mysql_query($sql,$conn);   
        }
        echo 'Table Created';   
    }

    fclose($handle);

}

?>