Skip to content

How to connect to a MSSQL Server With PHP

I recently had to connect to an MSSQL Server using PHP on an Ubuntu system using PHP. To connect to MSSQL using PHP 5.6 we’ll need to use PDO’s DBLIB (PDO_DBLIB). So let’s install the required packages using following commands:

Installing FreeTDS & Dependencies

$ sudo apt-get update
$ sudo apt-get install php5.6-sybase freetds-common libsybdb5
$ sudo service apache2 restart

All set!, now you should be able to get access to the SQL server database with PHP. Let’s test it with below code

prepare($query);
    $statement->execute();

    $results = $statement->fetchAll(PDO::FETCH_ASSOC);

    var_dump($results);


} catch (PDOException $e) {
    echo "Failed to get DB handle: " . $e->getMessage() . "\n";
    exit;
}

If you get error like below shown
SQLSTATE[01002] Adaptive Server connection failed (severity 9)

change the connection string parameters like shown below –

$pdo = new PDO ("dblib:version=8.0;charset=UTF-8;host={$hostname};dbname={$dbname}", $username, $pwd);
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments