【问题标题】:Load excel files using php/sql depending on filename根据文件名使用 php/sql 加载 excel 文件
【发布时间】:2015-11-03 19:05:07
【问题描述】:

我正在使用此代码在我的数据库中加载文件。这是我在putty上上传的一个php文件:

$Db->query('LOAD DATA LOCAL INFILE \'/name 03.11.2015.csv\'  
        INTO TABLE '.$in_table.'
        FIELDS TERMINATED BY \',\'
        ENCLOSED BY \'"\'
        LINES TERMINATED BY \'\n\'
        IGNORE 8 ROWS
        (@date, number, @name)
        set date=str_to_date(@date,\'%Y-%m-%d\'),
            name= \'name\'
        ;');

现在我想在查询的第一行有一个变量而不是一个特定的文件名:

$Db->query('LOAD DATA LOCAL INFILE \'/path/name 03.11.2015.csv\' 

所以,我正在使用它,它似乎正在工作:

$date = '.....';
$name = '.....';

    $Db->query('LOAD DATA INFILE \'/path/'.$name.' '.$date.'.csv\' 
            INTO TABLE '.$in_table.'
            FIELDS TERMINATED BY \',\'
            ENCLOSED BY \'"\'
            LINES TERMINATED BY \'\n\'
            IGNORE 8 ROWS
            (@date, number, @name)
            set date=str_to_date(@date,\'%Y-%m-%d\'),
                name= \'name\'
            ;');

但现在我必须更改我的代码,因为某些文件的文件名中没有这种格式:'$name $date'。下面给出一些例子:

  • 姓名 2015-10-10
  • 名称 2015-10-10

鉴于名称是特定值,我如何检查文件名?我想连接文件名并获取名称和日期以便找到文件,然后在我的代码中使用原始文件名。

【问题讨论】:

  • “特定值”是什么意思?
  • 例如它是“aaa”或“bbb”。所以,如果字符串(文件名)中有一个“aaa”,那么列名就是“aaa”。

标签: php mysql variables load


【解决方案1】:

我找到了这个问题的解决方案,但我仍然有一个与这个问题相关的未回答(链接在最后)。这个问题的答案就在这段代码中:

$searchString = 'aaaa';
$Dates = array();

// Get all the files in my folder with the extension ".xlsx"
$files = glob('/path/*.xlsx');

// I create an array where I save all the .xlsx files that contain "aaaa" in the filename
$filesFound = array();

foreach($files as $file) {
    $name = pathinfo($file, PATHINFO_FILENAME);

// Determines if there is a date and if the search string is in the filename. If yes, it puts the date and the filename in the arrays I created before
    if((strpos(strtolower($name),strtolower($searchString))) && (preg_match('~(\d{2}\.\d{2}\.\d{4})~', $name, $matches))) {
         $filesFound[] = $name;
         $Dates[] = $matches[1];
         foreach($filesFound as $ftbu){
            $sql = 'LOAD DATA LOCAL INFILE \'/path/'.$ftbu.'.xlsx\' INTO TABLE '.$dbtable.'
            FIELDS TERMINATED BY \',\' 
            ENCLOSED BY \'"\' 
            LINES TERMINATED BY \'\n\'
            (@date, number, @name)
            set date=str_to_date(@date,\'%Y-%m-%d\'),
                name = \'AAA\'
            ';
            $Db->query($sql);
            echo $Db->error;
        }
    } 
}

链接: Unanswered Question

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-05
    • 2020-10-21
    • 1970-01-01
    • 2017-12-18
    • 1970-01-01
    • 2010-09-13
    • 2019-11-29
    相关资源
    最近更新 更多