LOAD DATA INFILE - 还要为每一行添加此列条目?

时间:2014-05-21 02:41:39

标签: php mysql mysqli

以下是代码。

    $host = '';
    $username = '';
    $password = '';
    $database = '';
    $con = new mysqli($host,$username,$password,$database); 

    if ($con->connect_error) 
    {
        die('Connect Error (' . $mysqli->connect_errno . ') ' . $mysqli->connect_error);
    }

    $di = new RecursiveDirectoryIterator('/var/www/html/cdr');
    foreach (new RecursiveIteratorIterator($di) as $filename => $file) 
    {
        if ($filename == "/var/www/html/cdr/.")
        {

        } 
        else 
        {
            $con->query("LOAD DATA INFILE '" . $filename . "' 
                        INTO TABLE cdr 
                        FIELDS TERMINATED BY ',' 
                        ENCLOSED BY '\"'
                        LINES TERMINATED BY '\n'
                        IGNORE 1 LINES"
                        );
            echo $filename . " added to Database and deleted";
            echo "<br />";
            unlink($filename);
        }
    }

当前代码按预期工作。它通过csv文件目录进行迭代,并将每个文件导入数据库。

我想要做的是在标题为&#34; Filename&#34;的数据库中添加一个额外的列。使用每条记录来自的文件名。

有没有办法修改MySQL查询,在每行末尾添加指定的列数据,其中$ filename是数据?

感谢。

更新

以下是现在正在进行所需操作的更新代码。

    $di = new RecursiveDirectoryIterator('/var/www/html/cdr');
    foreach (new RecursiveIteratorIterator($di) as $filename => $file) 
    {
        $fileName = $filename;
        if ($fileName == "/var/www/html/cdr/.")
        {

        } else {
            $con->query("LOAD DATA INFILE '" . $fileName . "' 
                        INTO TABLE cdr 
                        FIELDS TERMINATED BY ',' 
                        ENCLOSED BY '\"'
                        LINES TERMINATED BY '\n'
                        IGNORE 1 LINES
                        SET filename = '" . $fileName . "'"
                        );
            echo $fileName . " added to Database and deleted";
            echo "<br />";
            unlink($fileName);
        }
    }

就像在查询结尾添加SET columnName = columnEntry一样简单。

1 个答案:

答案 0 :(得分:1)

你可以试试这个:

$sql = "LOAD DATA INFILE '" . $filename . "' 
                    INTO TABLE cdr 
                    FIELDS TERMINATED BY ',' 
                    ENCLOSED BY '\"'
                    LINES TERMINATED BY '\n'
                    IGNORE 1 LINES 
                    (`col2`,`col3`, `colX`)
                    SET filenameColumnName='{$filename}'";

甚至没有列列表:

$sql = "LOAD DATA INFILE '" . $filename . "' 
                    INTO TABLE cdr 
                    FIELDS TERMINATED BY ',' 
                    ENCLOSED BY '\"'
                    LINES TERMINATED BY '\n'
                    IGNORE 1 LINES
                    SET filenameColumnName='{$filename}'";

MySQL文档中有这样的例子:

http://dev.mysql.com/doc/refman/5.1/en/load-data.html

注意:您应该在查询中使用数据绑定,而不是直接包含$filename