【问题标题】:How do I export variable columns to a CSV file using PHP?如何使用 PHP 将变量列导出到 CSV 文件?
【发布时间】:2012-02-09 23:47:15
【问题描述】:

我知道如何使用 PHP 导出到 CSV 以查询 mySQL 并填充 CSV。但是,是否可以让用户选择他们想要的列并相应地改变 SQL 查询?

我已经建立了与数据库的连接,添加了我的查询:

$query = sprintf("SELECT x, y, z from a");
$result = mysql_query( $query, $conn ) or die( mysql_error( $conn ) );
header( 'Content-Type: text/csv' );
header( 'Content-Disposition: attachment;filename=export.csv' );
$row = mysql_fetch_assoc( $result );
if ( $row )
{
echocsv( array_keys( $row ) );
}
while ( $row )
{
echocsv( $row );
$row = mysql_fetch_assoc( $result );
}
function echocsv( $fields )
{
$separator = '';
foreach ( $fields as $field )
{
  if ( preg_match( '/\\r|\\n|,|"/', $field ) )
  {
    $field = '"' . str_replace( '"', '""', $field ) . '"';
  }
  echo $separator . $field;
  $separator = ',';
}
echo "\r\n";
}

【问题讨论】:

  • 是的,现在没有更多细节了。
  • 是的,这是可能的。在这种情况下,您必须以编程方式生成特定的 SQL 语句。
  • 如何以编程方式生成 SQL 语句?
  • 展示一些代码怎么样,我们至少有一个线索,你认为你提供了足够的信息让任何人能够帮助你吗?
  • 我已经添加了必要的代码。有任何想法吗?我收到未知的列名错误..

标签: php mysql select export-to-csv


【解决方案1】:

是的。您必须制作一个表单,用户选择他们要导出的字段,我正在考虑一个复选框列表,您可以在其中列出可以获取的所有可能的数据库字段,然后根据用户选择创建查询。 乙:

<form action="" method="post">
    <label><input name="fields[]" type="checkbox" value="name"> Username</label>
    <label><input name="fields[]" type="checkbox" value="birthdate"> Birthdate</label>
</form>

然后在服务器端创建数据库查询。

$sql = "SELECT `". implode("`, `", $_POST["fields"]) ."` FROM db_table";

希望对您有所帮助。

【讨论】:

  • 当我尝试使用它时,我得到了 - 字段列表中的未知列作者 - 错误。另外,我之前使用过这种类型的查询: $query = sprintf("select x from y");
猜你喜欢
  • 2015-12-04
  • 1970-01-01
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 2020-02-04
  • 2018-11-09
  • 2017-07-27
相关资源
最近更新 更多