Accessing MSSQL using PHP on Linux

clock
Portfolio item posted on Sunday, July 26th 2009 at 1:30 am
Bookmark and Share

Recently I had a project that required me to query a Microsoft SQL database from a PHP script running on one of my Linux servers. My Debian servers were not exactlly set up for this so it required me to do a little research.

Before I could even start writing my script I needed to install the proper PHP packages. I found many tutorials on setting up Linux servers to use ODBC connections but this seemed overly complicated and would require me to set up ODBC connections for every MSSQL database I wanted access to. Wanting something something simple and straight forward I found the PHP5-sybase package in the Debian package repository.

After doing `apt-get install php5-sybase` I was ready to dive into the php. The syntax for accessing a MSSQL database is almost identical to MySQL. First we needed to create our connection:

  1. $connection = mssql_connect("ServerName", "UserName", "Password")

Then we needed to specify which database on that server we wanted to access.

  1. $database = mssql_select_db("DatabaseName", $connection)

Once that is done we can start doing queries.

  1. $query = "SELECT info FROM dbo.TableName"
  2. $result = mssql_query($query);

Now we can print the output.

  1. while($row = mssql_fetch_array($result))
  2. {
  3.      echo $row["info"]."<br>";
  4. }

Make sure to close the connection when you are done!

  1. mssql_close($connection);

Hope this saves you some time, please feel free to leave comments.

One Response to “Accessing MSSQL using PHP on Linux”

  1. Elouise Meske says...

    Your blog is so informative ¡­ keep up the good work!!!!

Leave a Reply

Contact Us!