我正在运行如下所示的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";
答案 0 :(得分:2)
我写了一个创建单个导出的函数,然后在不同代码的循环中调用它。像这样:
function export($code)
{
$query = "select * from subscribers where list=27 and custom_fields LIKE '%\%" . $code . "\%%'";
// put the results for this query in $data as in your example
file_put_contents('/path/to/file/for/code_' . $code, $data);
}
$codes = array('CV', 'JCC', '...');
foreach ($codes as $code) {
export($code);
}