I am trying to connect to a SQL server database that is running on a windows server. I am running this PHP code on a linux server (centos 7).
I am using the following pdo connection string to connect to the database.
$db = new PDO ("dblib:192.168.2.1;dbname=TestDB","username",'pass');
When i run the code i get the following exception. 'PDOException' with message 'SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)'
I have tried to test the connection using tsql and i am able to connect to the database without any error. The following code gave me a list of all the tables in TestDB. It wouldnt work if i didng type use TestDB first.
tsql -S 192.168.2.1 -U username -P 'pass' -L TestDB
use TestDB
GO
select * FROM sys.Tables
GO
My freetds.conf file contains the following
[Server1]
host = 192.168.2.1
port = 1433
tds version = 8.0
I cannot figure out how i am able to connect using tsql, but cannot do the same when connecting with php.
The dblib driver is definitely installed.
print_r(PDO::getAvailableDrivers());
Array ( [0] => dblib [1] => mysql [2] => sqlite )
Answer
Found the cause of the problem. Turned out to be SELinux. The following commands fixed the issue.
setsebool -P httpd_can_network_connect 1
setsebool -P httpd_can_network_connect_db 1
You have the datasource name, you should make use of it:
$db = new PDO ("dblib:host=Server1;dbname=TestDB","username",'pass');
You are running linux right? I recommend giving odbc a shot.
Three things to check for you.
First try your connection using your defined port.
Instead of:
$db = new PDO ("dblib:192.168.2.1;dbname=TestDB","username",'pass');
try using this:
$db = new PDO("dblib:host=192.168.2.1:1433;dbname=TestDB","username",'pass');
Second, you should be sure if your SQL Server is configured to hear on port 1433. You can check this using the SQL Server Configuration Manager.
The third (if you run it on windows) thing you can check is one thing I find in the PHP docs. Inside a comment, another one mentioned the same error. Here is the answer which seems to work:
For PDO MSSQL connection issues, ensure that you have the updated version of ntwdblib.dll (currently 8.00.194 as of this post). Overwrite the existing (old) file or place it in the Windows system32 folder. The version that ships with PHP 5.2.X does not work. This is a well known issue apparently, but I had a really hard time finding information on this issue until I was able to lock in a file name. I hope that this helps someone.
Another possible issue could be SELinux if it's enabled. I've gotten some errors which are something familiar with this on my Ruby on Rails installation. You can give it a try by disabling SELinux and try it again.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With