Thursday 24 January 2013

Exporting MS SQL Table Data using PHP

I regularly export table data from MySQL using PHP, however a question on StackOverflow.com came up where the user wanted to export data from MS SQL rather than MySQL.

Handily, PHP has support for many of the same functions for MS SQL as it does for MySQL.

So with a bit of reworking I was able to come up with the following script;

<?php
    
    $servername = '.\SQLSERVER';
    $username = 'databaseuser';
    $password = 'database';
    $database = 'CriticalPath';
    $table = 'Users';
 
    if (!function_exists('mssql_fetch_row'))
    {
        $output .= "MSSQL functions are not available.<br />\n";
        exit;
    }
 
    // Connect database
    if(!$dbconnect = mssql_connect($servername, $username, $password))
    {
        $output .= "Connection failed to the host 'localhost'.";
        exit;
    } // if
        
    if (!mssql_select_db($database))
    {
        $output .= "Cannot connect to database '$database'";
        exit;
    } // if
    
    $result=mssql_query("select * from $table");
    
    $out = '';
 
    $columns = mssql_num_fields($result);    
 
    for ($i = 0; $i < $columns; ++$i) {
        // Fetch the field information
        $field = mssql_fetch_field($result, $i);
        $out .= '"'.$field->name.'",';
    }
       
    $out .= "\r";
    
    // Add all values in the table to $out.
    while ($l = mssql_fetch_array($result)) 
    {
       for ($i = 0; $i < $columns; $i++) 
       {
          $out .='"'.$l["$i"].'",';
       }
 
       $out .= "\r";
    }
    
    // Open file export.csv.
    $f = fopen ('export.csv','w');
    
    // Put all values from $out to export.csv.
    fputs($f, $out);
    fclose($f);
    
    header('Content-type: application/csv');
    header('Content-Disposition: attachment; filename="export.csv"');
    readfile('export.csv');
 
    mssql_free_result($result);
 
?>

No comments:

Post a Comment