2015-04-07 7 views
0

Мне нужна помощь для экспорта из запроса SQL Server в csv.PHP Экспорт в CSV с SQL Server

У меня есть запрос, но когда я получаю результат, мне нужно поместить его в переменную и экспортировать.

Это то, что у меня есть:

$query = 'select * from sqlserver_table'; 
$result = odbc_exec($conMsSql,$query); 

// this gives me the columns 
while(odbc_fetch_row($result)){ 
     $field1 = odbc_result($result, 1); 
     $field2 = odbc_result($result, 2); 
     $field3 = odbc_result($result, 3); 
     $field4 = odbc_result($result, 4); 
     $field5 = odbc_result($result, 5); 
     $field6 = odbc_result($result, 6); 
     $field7 = odbc_result($result, 7); 
    } 


// this is to export 
$file = fopen("export.csv","w"); 

foreach ($list as $line){ // how can I put the result in this variable ($list)? 
    fputcsv($file,explode(',',$line)); 
} 

fclose($file); 
+0

я не уверен, что речь идет именно. Можете быть более конкретными? В какой части описания запроса на csv возникают проблемы? – Commander

+0

Мне нужно поместить результат запроса в переменную $ list и вот где моя проблема, как передать ее переменной $ list. –

ответ

0

Вы бы хотели что-то вроде этого:

$csvName = "export.csv" 
$sqlQuery = 'select * from sqlserver_table'; 
$sqlRresult = odbc_exec($conMsSql, $sql); 

$fp = fopen(csvName , 'w'); 

while ($export = odbc_fetch_array($sqlRresult)) { 
    if (!isset($headings)) 
    { 
     $headings = array_keys($export); 
     fputcsv($fp, $headings, ',', '"'); 
    } 
    fputcsv($fp, $export, ',', '"'); 
} 
fclose($fp); 
+0

Thats it. Большое спасибо. –

0

позволяет сказать, что это был ваш SQL, вы могли бы сделать следующее, чтобы экспортировать данные из MSSQL в .csv.

$sql = "SELECT * FROM target_database_table_name"; 

$results = mssql_query($sql, $db); 
//Generate CSV file - Set as MSSQL_ASSOC as you don't need the numeric values. 
while ($l = mssql_fetch_array($results, MSSQL_ASSOC)) { 
    foreach($l AS $key => $value){ 
     //If the character " exists, then escape it, otherwise the csv file will be invalid. 
     $pos = strpos($value, '"'); 
     if ($pos !== false) { 
      $value = str_replace('"', '\"', $value); 
     } 
     $out .= '"'.$value.'",'; 
    } 
    $out .= "\n"; 
} 
mssql_free_result($results); 
mssql_close($db); 
// Output to browser with the CSV mime type 
header("Content-type: text/x-csv"); 
header("Content-Disposition: attachment; filename=table_dump.csv"); 
echo $out; 
+0

Спасибо или ваш ответ. С уважением. –

Смежные вопросы