Я экспортирую таблицу SQL Server в CSV, используя php (см. Код ниже). Мне нужна помощь, в том числе заголовки столбцов в экспорте. Я могу сделать это при экспорте из MySQL, но не могу понять это с помощью SQL Server. Если кто-нибудь может указать мне правильное направление, я был бы признателен.
<?php
// SQL Server connection string details.
$myServer = "server";
$myUser = "user";
$myPass = "password";
$myDB = "dbname";
// connection to the SQL Server
$dbhandle = mssql_connect($myServer, $myUser, $myPass)
or die("Couldn't connect to SQL Server on $myServer");
//select a database to work with
$selected = mssql_select_db($myDB, $dbhandle)
or die("Couldn't open database $myDB");
//declare the SQL statement that will query the database
$query = "SELECT col01, col02, col03, col04, col05, col06, col07 ";
$query .= "FROM table ";
$result = mssql_query($query, $dbhandle);
//Generate CSV file - Set as MSSQL_ASSOC as you don't need the numeric values.
while ($l = mssql_fetch_array($result, 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";
}
//free result set memory
mssql_free_result($result);
//close the connection
mssql_close($dbhandle);
// Output to browser with the CSV mime type
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=export.csv");
echo $out;
?>