将MySQL数据从不同的表传输到CSV文件

时间:2013-05-24 17:45:53

标签: php mysql csv

<?php
$server = 'localhost';
$login = 'user';
$password = 'pass';
$db = 'database';
$filename = 'output.csv';
$table = 'table';

mysql_connect($server, $login, $password);
mysql_select_db($db);

$fp = fopen($filename, "w");

$res = mysql_query("SELECT * FROM $table");

// fetch a row and write the column names out to the file
$row = mysql_fetch_assoc($res);
$line = "";
$comma = "";
foreach($row as $name => $value) {
    $line .= $comma . '"' . str_replace('"', '""', $name) . '"';
    $comma = ",";
}
$line .= "\n";
fputs($fp, $line);

// remove the result pointer back to the start
mysql_data_seek($res, 0);

// and loop through the actual data
while($row = mysql_fetch_assoc($res)) {
    $line = "";
    $comma = "";
    foreach($row as $value) {
        $line .= $comma . '"' . str_replace('"', '""', $value) . '"';
        $comma = ",";
    }
    $line .= "\n";
    fputs($fp, $line);
}

fclose($fp);
?>

我正在尝试将数据从Joomla网站导入CSV文件。使用Joomla扩展创建了如此多的数据库表,这使我的情况变得更加复杂。

我已经尝试了上面的代码,它给了我想要的初始结果,即创建一个包含来自一个数据库表的数据的CSV文件。现在,我想弄清楚的是如何创建相同的文件;但我从不同但相关的表中获取数据。

情况如下:

  • 表1包含可由表2,3记录的ID。
  • 不需要某些字段,只有选定的字段可以导出。

我将如何做到这一点?

$table1 = 'database_table1';
$table2 = 'database_table2';
$table3 = 'database_table3';
$table4 = 'database_table4';

$res = mysql_query("SELECT table1_field1, table1_field2 FROM $table1 t1
    INNER JOIN $table3 t3 table2_field1, table2_field2, table2_field3, table2_field4 ON t1.id = t3.pid
    INNER JOIN $table2 t2 table3_field1, table3_field2, table3_field3, table3_field4, table3_field5 ON t1.id = t2.content_id
    INNER JOIN $table4 t4 table4_field1, table4_field2 ON t3.id = t4.review_id
");

1 个答案:

答案 0 :(得分:1)

只需从以下位置更新您的sql语句:

$res = mysql_query("SELECT * FROM $table");

类似

$res = mysql_query("SELECT t1.title, t1.introtext,t2.jr_street, t2.jr_city, t2.jr_state, t2.jr_postalcode, t2.jr_country,t3.created, t3.name, t3.title, t3.comments, t4.rating_sum, t4.ratings_qty   FROM $table1 t1
                    INNER JOIN $table2 t2 ON t1.id = t2.content_id
                    INNER JOIN $table3 t3 ON t1.id = t3.pid
                    INNER JOIN $table4 t4  ON t1.id = t4.review_id
");

确保ID正确映射。