【问题标题】:Upload csv files to database将 csv 文件上传到数据库
【发布时间】:2014-07-09 08:21:47
【问题描述】:

大家好,我有一个问题,我想上传 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");
        }

?>

感谢您的帮助..

【问题讨论】:

  • 您能解释一下究竟是什么不起作用以及问题出在哪里吗?
  • '不起作用' - 简洁、准确且完全没用。解释应该发生什么以及实际发生了什么。 FWIW 你至少有一个错字:catch(pdoExecption $e)
  • 您收到什么错误信息?
  • 我没有错误重定向到 index.php
  • 嗨 @MikeW 当我上传 csv 文件时,没有发生任何错误,而是将我重定向到 index.php,这意味着成功......

标签: php mysql csv


【解决方案1】:

你的方法不可行。

要导入 CSV,您可以使用 mysqlimport 实用程序,或者您必须将 csv 记录拆分为单独的字段以匹配您的 INSERT 语句。您不能只将 CSV 提供给 insert 语句并希望它自己解决问题。

【讨论】:

  • 嗨,你能给我样品吗,我不知道,因为还是新手,提前谢谢。
【解决方案2】:

我可以给你一个我前段时间写的 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 循环中触发每个查询。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多