简体   繁体   English

通过php将csv文件上传到mysql

[英]uploading csv file into mysql through php

i know how to upload a csv file into mysql database but only through cmd. 我知道如何将csv文件上传到mysql数据库,但只能通过cmd。 i want to know how to upload csv file into mysql database using php form and will disregard some information on the excel and will only start importing starting from a certain line. 我想知道如何使用PHP表格将csv文件上传到mysql数据库,并忽略excel上的一些信息,只会从某一行开始导入。 ? kindly help me. 请帮助我。

(PHP 4, PHP 5) (PHP 4,PHP 5)

fgetcsv fgetcsv

See php manual http://php.net/manual/en/function.fgetcsv.php 请参阅php手册http://php.net/manual/en/function.fgetcsv.php

<?php
$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}
?>

Try this it's working well, you can add as many values as possible depending on the number of columns you have in the CSV file. 试试这个它运行良好,您可以根据CSV文件中的列数添加尽可能多的值。 Then in the HTML code put the uploading syntax in the tag. 然后在HTML代码中将上传语法放在标记中。

** **

$fname = $_FILES['csv_file']['name'];     
$chk_ext = explode(".",$fname);             

        $filename = $_FILES['csv_file']['tmp_     name'];   
$handle = fopen($filename, "r");      
if(!$handle){
die ('Cannot open file for reading');
}      
              while (($data = fgetcsv($handle,     10000, ",")) !== FALSE)
{
          $query = "INSERT INTO tablename       (col1_csv, col2_csv)
values ('$data[0]', '$data[1]');
mysql_query($query) or die(mysql_error    ());
}
 fclose($handle);
?>

** **

You can use the MySQL LOAD DATA INFILE statement to bulk-insert thousands of records at once. 您可以使用MySQL LOAD DATA INFILE语句一次批量插入数千条记录。 PHP can handle the file upload. PHP可以处理文件上传。 The PHP code would be something similar to: PHP代码类似于:

$query = sprintf("
    LOAD DATA LOCAL INFILE '%s'
    INTO TABLE `table1`
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
    LINES TERMINATED BY '\\r\\n'
    IGNORE 1 LINES
    ",
    mysql_real_escape_string($FILES["file1"]["tmp_name"])
);

The LOCAL keyword should allow you to workaround some security restrictions. LOCAL关键字应该允许您解决一些安全限制。 Change the FIELDS TERMINATED BY and LINES TERMINATED BY parameter to match the separators used by excel while exporting. 更改FIELDS TERMINATED BYLINES TERMINATED BY参数以匹配excel在导出时使用的分隔符。 IGNORE 1 LINES tells MySQL to skip the header row(s). IGNORE 1 LINES告诉MySQL跳过标题行。

Note: Excel does not seem to use an escape character; 注意:Excel似乎不使用转义字符; but it will (i) enclose the fields that contain , and " with " (ii) use "" to escape a single " inside data. I believe MySQL will understand this encoding and import the data correctly. 但它会(i)包含包含的字段,并且" with " (ii)使用""来逃避单个"内部数据。我相信MySQL会理解这种编码并正确导入数据。

try this: 尝试这个:

 $filename=$_FILES["upload_file"]["name"];
 $extension = end(explode(".",$filename));
 if ($extension=='csv') {
     $tmp_file=$_FILES["upload_file"]["tmp_name"];
     $handle = @fopen($tmp_file, "r");
     //specify your own database connection parameter
     $db = new PDO('mysql:host=localhost;dbname=demo','user','password');
     $stmt = $db->prepare("INSERT INTO writers (writer_name, writer_email) VALUES (?, ?)");
     if ($handle) {
        while (($buffer = fgets($handle, 4096)) !== false) {
            $array=explode(",",$buffer);
            $count=1;
            foreach ($array as $value) {
                $stmt->bindParam($count, $value);
                $count++;
            }
            $stmt->execute();
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
        }
        $db = null;
        echo "<p>Success</p>";
    }
    else {
        $error="<p style='color:red;'>Invalid file type</p>";
    }

Refer to http://pradipchitrakar.com.np/programming/upload-csv-mysql-php/ 请参阅http://pradipchitrakar.com.np/programming/upload-csv-mysql-php/

您可以使用“LOAD DATA INFILE”语句和“IGNORE ... LINES”选项,您可以从命令行以及PHP中使用该选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM