将csv文件上传到数据库

时间:2014-07-09 08:21:47

标签: php mysql csv

HI伙计我有问题我想上传csv文件并存储到数据库 但是不起作用.. 我尝试了几次调试,但没有工作希望你帮助我们。  我有一个包含..

的csv文件

firstname lastname middlename gender

test test test male

然后,当我上传此csv文件时,无法正常工作。

这是我的代码..

<?php 

    session_start();
        include ("config.php");



            $extension = end(explode(".",basename($_FILES['file']['name'])));

            if (isset($_FILES['file']) && $_FILES['file']['size'] < 10485760 && $extension== 'csv')
            {
                $file   = $_FILES['file']['tmp_name'];
                $handle = fopen($file, "r");

                try 
                {
                    $connection = new pdo("mysql:host=$hostname;dbname=upload",$username,$password);


                    if

                    $upload = $connection->prepare("INSERT INTO tbl_upload(firstname,lastname,middlename,gender)
                            VALUES (?,?,?,?)");

                    if($handle !== false)               
                    {

                        fgets($handle);
                        while (($data = fgetcsv($handle, 10000, ',') !== false))
                        {

                            $upload->execute($data);

                        }

                        fclose($handle);

                        $connection = null;

                        echo "<p class='bg-success'>Upload Success</p>";
                        header ("location: index.php");
                    }   

            }
            catch(pdoExecption $e)
            {   
                die($e->getmessage());
            }
        }

        else
        {
            header("location:config.php");
        }

?>

感谢您的帮助..

2 个答案:

答案 0 :(得分:0)

你的方法不可行。

要导入CSV,您可以使用mysqlimport实用程序,也可以在单独的字段中拆分csv记录以匹配INSERT语句。您不能只将CSV提供给insert语句,并希望它能为自己排序。

答案 1 :(得分:0)

我可以给你一些我前面写过的CsvImport类让导入CSV更容易一点

<?php
    final class CsvImport {
        private $file = "";
        private $fields = array(); //array("field1", "field2", "field3"); ...
        private $data = array(); //array([1] => array("value", "value", "value") ...
        private $delimiter = "";
        private $fieldCount = 0;
        private $rowCount = 0;
        private $internalCounter = 0;
        private $loaded = false;

        public function __construct($_file, $_delimiter = "") {
            $this->file = $_file;
            if(is_file($this->file) == true) {
                if(($handle = fopen($this->file, "r")) !== false) {
                    //If the delimiter is not set try to suggest it
                    if(strlen($_delimiter) == 0) {
                        $this->delimiter = $this->suggestDelimiter();
                    } else {
                        $this->delimiter = $_delimiter;
                    }
                    if(strlen($this->delimiter) > 0) {
                        $row = 0;
                        while(($data = fgetcsv($handle, 0, $this->delimiter)) !== false) {
                            if($row == 0) {
                                $this->fieldCount = count($data);
                            }
                            if($this->fieldCount > 0) {
                                for($c = 0; $c < $this->fieldCount; $c++) {
                                    if($row == 0) {
                                        $this->fieldCount = count($data);
                                        $this->fields[] = $data[$c];
                                    } else {
                                        $this->data[$row][$this->fields[$c]] = utf8_encode($data[$c]);
                                    }
                                }
                            }
                            $row++;
                        }
                        $this->rowCount = $row;
                        if($this->fieldCount > 0) {
                            $this->loaded = true;
                        }
                    }
                }
            }
        }

        public function getNextRow() {
            $retVal = false;

            if($this->loaded == true) {
                if($this->internalCounter < $this->rowCount) {
                    $this->internalCounter++;
                    $retVal = true;
                } else {
                    $this->internalCounter = 0;
                }
            }

            return $retVal;
        }

        public function readField($field) {
            $retVal = false;
            if($this->isLoaded() == true) {
                if(isset($this->data[$this->internalCounter][$field]) == true) {
                    $retVal = $this->data[$this->internalCounter][$field];
                }
            }

            return $retVal;
        }

        public function resetInternalCounter() {
            $this->internalCounter = 0;
        }

        public function getFieldCount() {
            return $this->fieldCount;
        }

        public function getRowCount() {
            return $this->rowCount;
        }

        public function getFieldList() {
            return $this->fields;
        }

        public function getDelimiter() {
            return $this->delimiter;
        }

        public function isLoaded() {
            return $this->loaded;
        }

        private function suggestDelimiter() {
            $retVal = "";

            $file = fopen($this->file, 'r');
            $content = fgets($file);
            fclose($file);

            if(strlen($content) > 0) {
                $list = array(
                    "," => substr_count($content, ","),
                    "." => substr_count($content, "."),
                    "&" => substr_count($content, "&"),
                    "%" => substr_count($content, "%"),
                    "-" => substr_count($content, "-"),
                    ";" => substr_count($content, ";"),
                    "'" => substr_count($content, "'"),
                    "\"" => substr_count($content, "\""),
                );

                $maxCount = 0;

                foreach($list as $key => $value) {
                    if($value > 0) {
                        if($value > $maxCount) {
                            $retVal = $key;
                            $maxCount = $value;
                        }
                    }
                }
            }

            return $retVal;
        }

        private function __clone() { }
    }
?>

用法很简单:

$file = "/path/to/file.csv";
$import = new CsvImport($file);
if($import->isLoaded() == true) {
    while($import->getNextRow()) {
        foreach($import->getFieldList() as $fieldName) {
            $value = $import->readField($fieldName);
            echo $fieldName . " => " . $value . "<br />";
        }
    }
}

我相信您可以使用foreach循环中的所有字段名构建查询,并在while循环中触发每个查询。

相关问题