将DATA加载到TABLE中而不插入数据

时间:2015-06-25 17:01:54

标签: php mysql csv

我正在尝试使用PHP将CSV文件中的数据导入到我的表中。我尝试使用完全相同的代码而不使用反斜杠来包含'"''在phpmyadmin上导入成功。

我还检查了管理员的用户权限。

这是我的代码:

<?php
error_reporting(E_ALL); ini_set('display_errors', 1);

$pdo = new PDO('mysql:dbname=mydatabase;host=localhost;charset=utf8', 'admin', 'admin');
$pdo->exec('SET CHARACTER SET utf8');
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try{
$query = $pdo->prepare("LOAD DATA LOCAL INFILE 'C:\feed.csv' IGNORE INTO TABLE tablename

fields terminated by ','
enclosed by '\"'
lines terminated by '\n'
IGNORE 1 LINES

(field1, field2, field3, field4)", array(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => true));

$query->execute();
$query->fetchAll();

} catch (PDOException $e) {
echo 'error: ' . $e->getMessage();
}
?>

运行此代码时,我看到此错误:

General error: 2014 Cannot execute queries while other unbuffered queries are active. Consider using PDOStatement::fetchAll(). Alternatively, if your code is only ever going to run against mysql, you may enable query buffering by setting the PDO::MYSQL_ATTR_USE_BUFFERED_QUERY attribute.

1 个答案:

答案 0 :(得分:0)

我的代码中没有错误,但您可以使用我的代码,我认为这对您有帮助

我已经实现了这段代码,它是经过测试的代码。我认为这是非常充分的使用

您遵循一些规则: -

1.您的csv文件根据数据库表名称(例如:db表名是用户,那么csv应该是users.csv)

2.您的csv文件的第一行应该是数据输入开始后的db表字段名称(例如:Id,name等)

3.您可以从以下网址下载数据源类: - http://code.google.com/p/php-csv-parser/因为我需要在代码下面:require_once&#39; CSV / DataSource.php&#39;;

<?php
ini_set('memory_limit','512M');
$dbhost = "localhost";
$dbname = "excel_import";
$dbuser = "root";
$dbpass = "";

$conn=mysql_connect ($dbhost, $dbuser, $dbpass) or die ("I cannot connect to the database because: " . mysql_error());
mysql_select_db($dbname) or die("Unable to select database because: " . mysql_error());


require_once 'CSV/DataSource.php';


$filename = "users.csv";
$ext = explode(".",$filename);
$path = "uploads/".$filename;

$dbtable = $ext[0];

import_csv($dbtable, $path);


function import_csv($dbtable, $csv_file_name_with_path)
{
    $csv = new File_CSV_DataSource;
    $csv->load($csv_file_name_with_path);

    $csvData = $csv->connect();

    $res='';
    foreach($csvData  as $key)
    {
        $myKey ='';
        $myVal='';
        foreach($key as $k=>$v)
        {
            $myKey .=$k.',';
            $myVal .="'".$v."',";
          }

        $myKey = substr($myKey, 0, -1);
        $myVal = substr($myVal, 0, -1); 
        $query="insert into ".$dbtable." ($myKey)values($myVal)";
        $res=  mysql_query($query);

    }

    if($res ==1)
    {

                echo "record successfully Import.";

    }else{

                echo "record not successfully Import.";
    }
}