<?php
$host = “”;
$user = “”;
$pass = “”;
$name = “”;
ini_set(‘display_errors’,on);
backup_tables(”,”,”,”);

/* backup the db OR just a table */
function backup_tables($host,$user,$pass,$name,$tables = ‘*’)
{
 
  $link = mssql_connect($host,$user,$pass);
  mssql_select_db($name,$link);
 
  //get all of the tables
  if($tables == ‘*’)
  {
    $tables = array();
    $result = mssql_query(“SELECT * FROM INFORMATION_SCHEMA.TABLES AS data WHERE TABLE_TYPE = ‘BASE TABLE'”);
    //print_r($result);
    while($row = mssql_fetch_row($result))
    {
      $tables[] = $row[2];
    }
  }
  else
  {
    $tables = is_array($tables) ? $tables : explode(‘,’,$tables);
  }
 
  //cycle through
  foreach($tables as $table)
  {
    $result = mssql_query(‘SELECT * FROM ‘.$table);
    $num_fields = mssql_num_fields($result);
    
    $return.= ‘DROP TABLE ‘.$table.’;’;
    
     $return.= ‘CREATE TABLE ‘.$table.’;’;
    
    //$row2 = mssql_fetch_row(mssql_query(‘SHOW CREATE TABLE ‘.$table));
    
    //EXEC sp_help <table_name>
    //exec sp_columns MyTable
    
    $result1 = mssql_query(‘exec sp_columns ‘.$table);
    $num_fields1 =  mssql_num_fields($result);
     for ($i = 0; $i < $num_fields1; $i++)
    {
      while($row1 = mssql_fetch_row($result1))
      {
                 
            $return.= $row1[3];
            $return.= $row1[5];
        
        $return.= “);\n”;
      }
    }
    
  // echo $return.= “\n\n”.$row2[2].”;\n\n”;
    
    for ($i = 0; $i < $num_fields; $i++)
    {
      while($row = mssql_fetch_row($result))
      {
        $return.= ‘INSERT INTO ‘.$table.’ VALUES(‘;
        for($j=0; $j<$num_fields; $j++)
        {
          $row[$j] = addslashes($row[$j]);
          $row[$j] = ereg_replace(“\n”,”\\n”,$row[$j]);
          if (isset($row[$j])) { $return.= ‘”‘.$row[$j].'”‘ ; } else { $return.= ‘””‘; }
          if ($j<($num_fields-1)) { $return.= ‘,’; }
        }
        $return.= “);\n”;
      }
    }
    $return.=”\n\n\n”;
  }
 
  //save file
  $handle = fopen(‘db-backup-‘.time().’-‘.(md5(implode(‘,’,$tables))).’.sql’,’w+’);
  fwrite($handle,$return);
  fclose($handle);
}
?>