0
<?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
");
4

1 回答 1

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 映射正确。

于 2013-05-24T18:02:25.810 回答