Exporting data from SQL Server Express 2005 to CSV using PHP

By David Pratt / Tags: , / 5 Comments / Published: 10-06-11

Annoyingly, one of the limitations of SQL Server Express 2005 is that it doesn’t allow you to export data as CSV, or any other format (bar SQL) for that matter. This is fine is you have a small dataset as you can just copy the data out of the results pane, and then paste into a spreadsheet program to save in the format of your choosing. If like me on the other hand whereby you have a massive result set of +100k records then that doesn’t quite work.

Googleing around for a solution I came across a couple of different options (using DTS Wizard, another using a 3rd party app etc.), but nothing looked like it could do the job I was after – basically I wanted a no-fuss phpmyadmin style export to csv option. Dissatisfied with the options out there, I ended up deciding to write a php script that would connect to the db using the mssql php extension, get the required data, and automatically spit out a csv file. Writing the script was the easy part, the difficult bit was getting PHP to talk to the database due to an incompatibility between the SQL Server Express 2005 db driver and the php extension. To get PHP to play nicely with MS SQL Server 2005 Express you need to resolve this driver problem, here’s how you do it:

  1. Search your computer for ntwdblib.dll
  2. If you right click on each occurance of the file (I had one in the php, apache and system32 directories)
  3. Hit the details tab, and if any of them say a number that ISN’T 2000.80.194.0 then you need to download that version of the file.
  4. Once you have downloaded the file, you need to replace all of the existing ntwdblib.dll files with the one you have downloaded, or figure out which one your php version is using. Obviously, make back-ups first.

A more in depth tutorial on how to do this can be found
here.

Here’s the code for connecting to the db, generating a CSV file and outputting to file in the simplest way I could come up with:

//MSSQL connection string details.
$dbhost = "LOCALHOST\SQLEXPRESS";
$dbuser = 'dave';
$dbpass = 'password';
$dbname = 'target_db_name';
$db = mssql_connect($dbhost, $dbuser, $dbpass);
if (!$db) {
	die('Could not connect to mssql - check your connection details & make sure that ntwdblib.dll is the right version!');
}
$db_selected = mssql_select_db($dbname, $db);
if (!$db_selected) {
	die('Could not select mssql db');
}
$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;

For reference, I’m using PHP 5.2.3 on wamp – the driver fix mentioned above didn’t seem to work with 5.3.*

Category: Tech

Tags: ,

Posted: on June 10th, 2011 at 10:55 am.

Feeds: RSS 2.0

5 Responses to “Exporting data from SQL Server Express 2005 to CSV using PHP”

G December 12th, 2011 at 7:11 am

I wish there was a like button for this post :)

Mr. E. December 13th, 2011 at 7:19 pm

This is a great idea. One problem though: it does escape a quotation mark … but only the first one. If there are two, only the first gets escaped, no?

RJ January 12th, 2012 at 7:45 pm

Thanks for the script. Is there anyway to include the field names in the dump?

rashmi March 19th, 2012 at 7:54 am

Hi, Thanks for the script. Good One

sato June 22nd, 2012 at 9:35 pm

please you help how can i generate to text file (php+mssql) i’m trying about 2 days but can’t , many thank

Leave a reply