Skip to content

Instantly share code, notes, and snippets.

@joecampo
Last active June 4, 2022 14:20
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save joecampo/acd1e5881aee08bd8959 to your computer and use it in GitHub Desktop.
Save joecampo/acd1e5881aee08bd8959 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);
@tomtomklima
Copy link

I have a similar problem - after initializing PDO there is only null there. Using Ubuntu, PHP 5.6 and connecting into Microsoft SQL 2000

@rblew13
Copy link

rblew13 commented Nov 20, 2018

Worked like a charm! Thanks.

@mchogithub
Copy link

apt-get install php5-sybase freetds-common libsybdb5 WORKS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment