将多个SQL数据库导出到一个CSV

时间:2016-05-20 22:29:14

标签: php mysql csv

我之前在其他网站上看到过这种情况,但经过几天的努力,我似乎​​无法让它发挥作用。

我有两个表:“projects_2016”和“attachment”。

我想将数据导出到一个CSV文件中。到目前为止我只能导出“projects_2016”数据没问题。但是我希望显示“projects_2016”中的单行数据,然后如果“ids”匹配则会在下面列出“附件”的结果。

以下是屏幕上显示内容的屏幕截图,我希望它与此相同。 https://dl.dropboxusercontent.com/u/52977510/example.jpg

这是我到目前为止的代码。

<?php include '../../../connection_config.php'; 

$output = "";
$sql = mysql_query("SELECT DISTINCT id, project_name FROM projects_2016 
                    WHERE EXISTS 
                         (SELECT * FROM attachment 
                          WHERE projects_2016.id =  attachment_ABE_project_number) 
                          ORDER BY `id` DESC");

$columns_total = mysql_num_fields($sql);

for ($i = 0; $i < $columns_total; $i++) {
    $heading = mysql_field_name($sql, $i);
    $output .= '"'.$heading.'",';
}
$output .="\n";

while ($row = mysql_fetch_array($sql)) {
    for ($i = 0; $i < $columns_total; $i++) {
        $output .='"'.$row["$i"].'",';
    }
    $output .="\n";
}

$filename = "2t.csv";
header('Content-type: application/csv');
header('Content-Disposition: attachment; filename='.$filename);

echo $output;
exit;

?>

修订代码:

<?php

$host="localhost";
$username="basic";
$password="redrobinX123";
$database = "basic_TEST_gauteng"; 


try {
$dbh = new PDO($host,$database,$username,$password);    
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// EXECUTE QUERY
$sql = "SELECT DISTINCT p.*, a.*
        FROM projects_2016 p
        INNER JOIN attachment a
        ON p.id =  a.attachment_ABE_project_number
        ORDER BY `id` DESC";                          
$STH = $dbh->query($sql);    

// FETCH SQL QUERY RESUTS
$results = $STH->fetchAll(PDO::FETCH_ASSOC);

// OPEN CSV IN WRITE MODE
$filename = '/path/CSV/Output.csv';
$fp = fopen($filename, 'w');

// WRITE TO CSV ITERATIVELY IN NESTED LOOP       
foreach($results as $outer) {
    fputcsv($fp, array('PNo', 'Project Name'));                   # HEADERS
    fputcsv($fp, array($outer['PNo'], $outer['Project Name']));   # ROWS

    foreach($results as $inner) {
        if ($inner['id'] == $outer['id']) {
            fputcsv($fp, array('File Name', 'File Type', 'File Size (KB)',     'View'));
            fputcsv($fp, array($inner['File Name'], $inner['File Type'], 
                               $inner['File Size'], $inner['View']));
        }
    }

}

// CLOSE CSV
fclose($fp);       

catch(PDOException $e) {  
echo $e->getMessage()."\n";
exit;
}

// CLOSE DB CONNECTION
$dbh = null;

&GT;

1 个答案:

答案 0 :(得分:0)

考虑以下PDO示例(因为mysql_ *是deprecated,甚至是PHP中的removed),它获取数据库记录并使用fputcsv迭代地将行写入csv。

您的主要问题是您的SQL语句仅检索了projects_2016数据而非附件数据。如下所示,使用连接查询:

try {
    $dbh = new PDO("mysql:host=$host;dbname=$database",$username,$password);    
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // EXECUTE QUERY
    $sql = "SELECT DISTINCT p.*, a.*
            FROM projects_2016 p
            INNER JOIN attachment a
            ON p.id =  a.attachment_ABE_project_number
            ORDER BY `id` DESC";                          
    $STH = $dbh->query($sql);    

    // FETCH SQL QUERY RESUTS
    $results = $STH->fetchAll(PDO::FETCH_ASSOC);

    // OPEN CSV IN WRITE MODE
    $filename = '/path/CSV/Output.csv';
    $fp = fopen($filename, 'w');

    // WRITE TO CSV ITERATIVELY IN NESTED LOOP       
    foreach($results as $outer) {
        fputcsv($fp, array('PNo', 'Project Name'));                   # HEADERS
        fputcsv($fp, array($outer['PNo'], $outer['Project Name']));   # ROWS

        foreach($results as $inner) {
            if ($inner['id'] == $outer['id']) {
                fputcsv($fp, array('File Name', 'File Type', 'File Size (KB)', 'View'));
                fputcsv($fp, array($inner['File Name'], $inner['File Type'], 
                                   $inner['File Size'], $inner['View']));
            }
        }   
    }
    // CLOSE CSV
    fclose($fp);       
}    
catch(PDOException $e) {  
    echo $e->getMessage()."\n";
    exit;
}

// CLOSE DB CONNECTION
$dbh = null;