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
1 2 3 |
$ 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
<?php try { $hostname = 'xxx.database.windows.net'; $dbname = 'arjun_database_dev'; $username = 'arjun'; $pdo = new PDO ("dblib:host={$hostname};dbname={$dbname}", $username, $pwd); $query = "SELECT * FROM location"; $statement = $pdo->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 –
1 |
$pdo = new PDO ("dblib:version=8.0;charset=UTF-8;host={$hostname};dbname={$dbname}", $username, $pwd); |
I hope you like this Post, Please feel free to comment below, your suggestion and problems if you face - we are here to solve your problems.
I am Arjun from Hyderabad (India). I have been working as a software engineer from the last 7+ years, and it is my passion to learn new things and implement them as a practice. Aside from work, I like gardening and spending time with pets.