我有以下PHP,它会以CSV格式将结果返回给我查询,但顶部显示的LIKE语句中的代码(两个字母)需要在多个不同的代码之间进行更改.
CV,LC,RCA,JOR等……
并让脚本为每个不同的代码创建一个新的CSV,然后快速地逐个处理每个代码.所以我最终得到了30个文件.我可能需要这样做几次,所以手动更改它30次不是我的首选.
PHP
// database variables
$hostname = "localhost";
$user = "###";
$password = "###";
$database = "###";
$select = "select * from subscribers where list=27 and custom_fields LIKE '%\%CV\%%'";
$con = MysqL_connect($hostname,$user,$password);
$db_selected = MysqL_select_db($database,$con);
// Check connection
if (!$con)
{
die('Could not connect: ' . MysqL_error());
}
$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=list-export.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
?>
最佳答案
正如Mike W所说,你只需要一个包含你的代码的数组,如下所示:
$codes = array(“CV”,“LC”,“RCA”,“JOR”等……)
$codes = array(“CV”,“LC”,“RCA”,“JOR”等……)
//...
// connection has been checked
foreach($codes as $single_code){
// do the file-writing-stuff here,using $single_code to generate each query
}
// ...
为什么不考虑查询中的两个字段(从订户中选择FIELD1,FIELD2 ……)?
如果这些字段名称因代码而异,您可以使用以下内容:
>将数组声明为
$codes = array(“CV”=>“field_a,field_b”,“LC”=>“field_c,field_d”,…)
>生成查询如下
foreach($code as $single_code){
$select =“select $codes [$single_code]来自订阅者,其中list = 27,custom_fields LIKE’%$single_code%’”;
// …
}