Thursday, December 15, 2011

Installing and Using MSSQL from PHP on Centos5/RHEL5

The boss wants to use an MSSQL (a Sybase derivative) to power a PHP page on Linux.  You're thinking to yourself that the boss has finally lost it as you nod and smile politely.

Thing is, it's possible. And it's actually not so hard.  Installing it is tricky;  it's like this:
  1. yum install php-mssql
That's it.  It'll pull in both freetds (from EPEL) and unixodbc if it's not already installed.  How easy was that?  Okay, you may need to install the EPEL repository as well, but that's cake.

Now to use it.  Here's a sample.php:
sed 's:#:<:' <<-EOF >/tmp/sample.php
#?php
try {
  if (function_exists("mssql_connect")) {
    if (($m = mssql_connect("db.host.com:1433", "user", "passwd")) !== FALSE) {
      if (function_exists("mssql_query")) {
        $res = mssql_query("SELECT @@VERSION", $m);
        $row = mssql_fetch_array($res);
        print_r($row);
      } else
        throw new Exception("mssql_query function doesn't exist");
    } else
      throw new Exception("connection failed");
  } else
    throw new Exception("mssql_connect function doesn't exist");
  mssql_close($m);
} catch(Exception $e) {
  echo "#PRE>";
  print_r($e);
  echo "#/PRE>";
}
?>
EOF
And that should easily return a valid query and response.  And that's nice, because while the boss may well be crazy, his crazy grin looks better over free coffees.

Labels: , , , ,