Thursday 15 August 2013

Connecting Microsoft SQL Server with PHP on Ubuntu



Here is how to get PHP 5.3 on Linux (specifically Ubuntu) talking to a Microsoft SQL Server database:

  1) Install FreeTDS and the PHP MS SQL extension

sudo apt-get install freetds-common freetds-bin unixodbc php5-sybase

  2) Restart Apache

sudo /etc/init.d/apache2 restart

  3) Configure FreeTDS

  Add this at the end of the file:
[yourserver]
host = your.server.name
port = 1433
tds version = 8.0
Test connection to the MSSQL server with this PHP script
<?php
 $server = 'your server name';
 $username = 'enter';
 $password = 'enter';
 $database = 'enter';
 $connection = mssql_connect($server, $username, $password);
 if($connection != FALSE)
  {
  echo "Connected to the database server OK<br />";
  }
 else
  {
  die("Couldn't connect");
  }
 
 if(mssql_select_db($database, $connection))
  {
  echo "Selected $database ok<br />";
  }
 else
  {
  die('Failed to select DB');
  }

 $query_result = mssql_query('SELECT @@VERSION');
 $row = mssql_fetch_array($query_result);
  if($row != FALSE)
  {
  echo "Version is {$row[0]}<br />";
  }
 mssql_free_result($query_result);
 mssql_close($connection);
 ?>

   

No comments:

Post a Comment