Last active
December 16, 2015 19:30
-
-
Save alfredxing/5485756 to your computer and use it in GitHub Desktop.
Saving SQL Server query data to a CSV file (query from GET/POST request)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Connect to SQL server (SQLSRV can also be used, I used MSSQL because Native Client isn't needed) | |
* Replace <server>, <username>, and <password> with the appropriate details | |
*/ | |
$link = mssql_connect("<server>", '<username>', '<password>'); | |
if (!$link) | |
{ | |
die('Something went wrong while connecting to MSSQL'); | |
} | |
// I used a GET query for debugging (to access with URL), but POST probably works better in production | |
if (isset($_GET["q"])) : | |
$query = mssql_query($_GET["q"]); | |
$fields = mssql_num_fields ( $query ); | |
$header = ""; | |
$data = ""; | |
for ( $i = 0; $i < $fields; $i++ ) | |
{ | |
$header .= mssql_field_name( $query , $i ) . ","; | |
} | |
while( $row = mssql_fetch_row( $query ) ) | |
{ | |
$line = ''; | |
foreach( $row as $value ) | |
{ | |
if ( ( !isset( $value ) ) || ( $value == "" ) ) | |
{ | |
$value = ","; | |
} | |
else | |
{ | |
$value = str_replace( '"' , '""' , $value ); | |
$value = '"' . $value . '"' . ","; | |
} | |
$line .= $value; | |
} | |
$data .= trim( $line ) . "\n"; | |
} | |
$data = str_replace( "\r" , "" , $data ); | |
if ( $data == "" ) | |
{ | |
$data = "\n(0) Records Found!\n"; | |
} | |
header("Content-type: text/csv"); | |
header("Content-Disposition: attachment; filename=data.csv"); | |
header("Pragma: no-cache"); | |
header("Expires: 0"); | |
print "$header\n$data"; | |
else : | |
echo "SQL query not defined."; | |
endif; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment