Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save huzemin/3bfd4964b986c56cabb70a20c904fb7d to your computer and use it in GitHub Desktop.
Save huzemin/3bfd4964b986c56cabb70a20c904fb7d to your computer and use it in GitHub Desktop.
Connecting PHP 5.6 to MSSQL - Ubuntu (Debian) w/ Apache

To connect to MSSQL using PHP 5.6 we'll need to use PDO's DBLIB (PDO_DBLIB) http://php.net/manual/en/ref.pdo-dblib.php and FreeTDS http://www.freetds.org/

This quick tutorial is using Ubuntu Server 14.04

First, make sure you're up to date on all of your packages.

  • sudo apt-get update
  • sudo apt-get upgrade
  • sudo apt-get dist-upgrade

I'm using PHP 5.6.9 (https://launchpad.net/~ondrej/+archive/ubuntu/php5-5.6)

Installing FreeTDS & Dependecies

  • sudo apt-get install php5-sybase freetds-common libsybdb5
  • sudo apache2ctl restart

All Done

If all the dependencies install, you should be good to go! I've copied some sample code on how to create a query using prepared statements.

-Joe

try {
    $pdo = new \PDO(
        sprintf(
            "dblib:host=%s;dbname=%s",
            MSSQL_HOST,
            MSSQL_DATABASE
        ),
        MSSQL_USERNAME,
        MSSQL_PASSWORD
    );
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    echo "There was a problem connecting. " . $e->getMessage();
}
 
$query = "SELECT * FROM MyTable WHERE Username = :username";
 
$statement = $pdo->prepare($query);
$statement->bindValue(":username", "sanitizeduserinputusername", PDO::PARAM_STR);
$statement->execute();
 
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
 
var_dump($results);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment