【发布时间】:2014-11-11 13:56:44
【问题描述】:
我正在运行如下所示的 sql 来选择我的数据库中具有已定义兴趣代码的所有行。现在我想将所有选择的结果导出到 CSV 中,但这会发生大约 30 次,因为大约有 30 个兴趣代码。有没有办法让我一个接一个地循环遍历 1 个 sql,每次都使用新 SQL 查询的结果创建一个新的 CSV?
两个 sql 查询的示例。
select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%';
select * from subscribers where list=27 and custom_fields LIKE '%\%JJC\%%';
等等...每次都创建一个全新的 CSV 文件。 30 个文件。
我发现了以下内容(尚未测试),但我想这将是 php,但需要它继续通过 1 个 sql。
$select = "select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%';";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
【问题讨论】: