How to use MS SQL Server from PHP 5.x on Linux

Short answer: don’t. It’s a world of pain.

If you really must, keep reading.

Install the required packages

I’ll assume you already have a working webserver and PHP installation, along with the EPEL and Remi repositories.

yum --enablerepo=epel --enablerepo=remi install php-mssql freetds

Make sure the mssql library is loaded

cat /etc/php.d/mssql.ini
; Enable mssql extension module

Configure mssql

In /etc/php.ini make sure these two lines are set like this:

mssql.textlimit = 20971520
mssql.textsize = 20971520

Configure freetds

Edit /etc/freetds.conf to change the text size value and to create a new entry:

  text size = 20971520
  host =
  instance = instance_name
  port = 1433
  client charset = UTF-8
  tds version = 8.0
  text size = 20971520

You can omit the instance parameter if you are going to use the default.

Restart Apache and PHP

service httpd configtest && service httpd restart

Test the configuration

Create a simple php script, mssql_test.php:


$host_db = "mssqltest";  // reference to the name you used in /etc/freetds.conf
$user_db = "your_user";
$pass_db = "your_pass";
$name_db = "your_db_name";

$conn_db = mssql_connect($host_db, $user_db, $pass_db)
  or die("Connection failed to $host_db: " . mssql_get_last_message() . "\n\n");

$dbh     = mssql_select_db($name_db, $conn_db)
  or die("Cannot open DB $name_db: " . mssql_get_last_message() . "\n\n");

echo 'Connected.';

$query_results = mssql_query('SELECT * from YourTable')
  or die ("Cannot run your query: " . mssql_get_last_message() . "\n\n");

$row = mssql_fetch_array($query_results)
  or die ("Cannot fetch row: " . mssql_get_last_message() . "\n\n");

echo "$row\n\n";