【问题标题】:Transferring MySQL Data from Different Tables to a CSV file将 MySQL 数据从不同的表传输到 CSV 文件
【发布时间】:2013-05-24 17:45:53
【问题描述】:
<?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 包含一个 ID,可以通过表 2、3 进行跟踪。
  • 有些字段不需要,只有选定的字段要导出。

我该怎么做?

$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
");

【问题讨论】:

  • 你的意思是每个表都有不同的字段,你不知道如何动态地解决这个障碍?
  • @Ohgodwhy,我想要实现的是.. 而不是 "SELECT * FROM" 单个数据库表,我想从四个不同的表中获取我需要的数据。

标签: php mysql csv


【解决方案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 映射正确。

【讨论】:

  • t1 t2t3 数据库表吗?为什么是FROM $table t1
  • 这些是表的别名。我们需要在它旁边提到表别名,例如$table t1。另外,请确保在脚本开头添加 $table = 'table'; 之类的行。
  • 请查看我编辑的问题。底部的代码是我尝试过的代码。我的查询出现错误。请帮忙。谢谢。
  • 我仍然遇到同样的错误。您确定我们将获得所有数据FROM $table1 t1(在查询的第一部分)。
  • 这些只是警告,mysql 语句有问题。适当地加入表格。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-15
  • 2021-05-08
  • 2012-02-15
  • 2016-01-17
相关资源
最近更新 更多