We’re assuming you’ve already got MS SQL Server running on an Ubuntu machine. If you haven’t, take a look at our installation guide to get up to speed. We’ll be using Ubuntu, but the instructions aren’t that much different for RHEL or others.

Install PHP Extensions

Using PEAR, you’ll need to install and configure a few extensions for PHP to be able to access the MS SQL Server. PHP comes with the PHP Data Objects interface that provides a common way to access many different databases, but you need to install an extension for MS SQL Server to be able to use it PDO.

To install them, run the following PEAR command:

sudo pecl install sqlsrv pdo_sqlsrv

Then configure PHP to use the new extensions using bash (note the sudo!):

Connect to the Database

Now that PHP’s PDO knows how to interact with MS SQL Server, you can use it to connect to the server and run database commands. To establish a connection, use the global $sqlserv_connect function. For example, to connect to a local server:

Run that on the command line and you should see “Got a connection!” indicating that you were successfully connected to the database. The hard part is over! All that’s left is running some commands on the connection.

Execute Queries

Let’s assume you’ve got a simple SQL table set up to track employees in your organization, with fields for employee name, id, and work site. You’d like to run INSERT and UPDATE queries to add employees and change their data as part of your web application. Once you’ve got the connection set up as above, you can execute any command you’d like. To insert new users:

Notice how we use the $conn object we created above, and pass it to the global function sqlsrv_query. We also pass in a T-SQL statement and the associated parameters. Once the statement is executed, you also need to check to make sure you got a valid result.

Updates work the same way. We can change just the $tsql statement and get a working update:

Best Practices

Now that you’ve got a running application, be sure to check out the documentation on PDO. In particular, you’ll want to confirm after each statement that you execute that you got a correct result and that you got no errors. If you’re having trouble with your MS SQL Server on Linux, the “print_r( sqlsrv_errors(), true)” statement can be very helpful in debugging.

As the PHP driver is relatively young, you might also want to check out the GitHub page and the official documentation for new releases and for explanations of how to work around known issues.