php dblib, Error: SQLSTATE[HY000] Unknown host machine name (severity 2) - php

I am using mac computer OSX 10.9. Freetds and unixODBC are already installed on my computer and added as extension to php , trying to connect to a remote MSSQL server. Below is my connection testing:
<?php
$dbh = new PDO('dblib:host=Hostname ;dbname=Dbname', 'user', 'pw');
if (!$dbh) {
die('Something went wrong while connecting to MSSQL');
}
?>
The error logs file show :
[error] [client 127.0.0.1] PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] Unknown host machine name (severity 2)
What could be the problem ? It seems that my freetds and unixODBC are working fine if I use terminal to connect to the same database as below:
$ isql Hostname user pw
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>
and
$ tsql -S Hostname -U user
Password:
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
1>
here is my freetds.conf
[global]
# TDS protocol version
tds version = 8.0
[Hostname]
host = IP
port = 1433
tds version = 8.0
client charset = UTF-8 ##needed on MAC OS X
dump file = /tmp/freetds.log
and my odbc.ini
[Hostname]
#Driver=/usr/local/lib/libtdsodbc.so
Driver = /usr/local/Cellar/freetds/0.91_2/lib/libtdsodbc.so
Trace=No
Server=IP
Port=1433
TDS_Version=8.0
client charset = UTF-8
my phpinfo() shows that the extension has been added, there is dblib in PDO section and pdo_dblib section have driver Flavour enabled freetds.
So what is the problem? Any idea of what I should do ?
Any assistance will be highly appreciated.
here is my odbcinst.ini:
[freetdS]
Description = v0.63 with protocol v8.0
Driver = /usr/local/Cellar/freetds/0.91_2/lib/libtdsodbc.so

I actually solved this question by deleting both mssql.so, pdo_dblib.so in php extension folder, re-download php5.4 , phpize and build both the .so files again and put it back. Then it works.
It seems that the olde pdo_dblib.so file I made pointed to a different freetds.conf somewhere else.

Since it is not possible to debug this by proxy without real files information and you've opted to protect ip addresses and hostnames with dummy text. I am going with the PHP code. The hostname should be a FQDN or an ip address. Not the place holder text from the ini files.
<?php
$dbh = new PDO('dblib:host=[ ip address || example.com || localhost] ;dbname=Dbname', 'user', 'pw');
if (!$dbh)
{
die('Something went wrong while connecting to MSSQL');
}
?>

Related

How to connect to sybase from PHP in UNIX using ODBC+FreeTDS?

I have tried to connect sybase from terminal using FreeTDS and it is working fine but I am not able to connect database using PHP.
I have done changes in below files.
/etc/odbc.ini file:
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
Server =
Port =
Database =
Username =
Password =
freetds.conf file
[sybase]
host=
port=
Tds version=5.0
It is working fine using Terminal
tsql -S SYBASE -U username -P password
But from PHP connection I am getting error:
[unixODBC][Driver Manager]Data source name not found, and no default driver specified
PHP file code:
$db = ADONewConnection('odbc');
$DSN ='UID=username;PWD=password;EngineName=dbServiceName;AutoStop=No;Integrated=No;Debug=No;DisableMultiRowFetch=No;CommLinks=SharedMemory,TCPIP{};Compress=No;Driver={FreeTDS}';
$db->Connect($DSN );
I know in some versions, you need to use the IP of the server rather than the name, like this in freetds.conf:
[myserver]
host = 10.10.10.10
port = 5000
tds version = 5.0
I also don't know if tds version is case sensitive, but I've always seen it in lowercase. Are you sure that PHP is reading from the same freetds.conf that the command line version is?

SQLSTATE[01002] Adaptive Server connection failed (severity 9) error on Ubuntu Linux VPS

I am trying to connect to an Azure Microsoft SQL Server database on my php scripts. I cannot figure out why it isn't working. When I run my db_connection.php script, I get this error:
SQLSTATE[01002] Adaptive Server connection failed (severity 9)
When I run the tsql command, with the connection details for my azure ms sql database, the connection seems to work (I read the "1>" means the connection worked):
locale is "C"
locale charset is "ANSI_X3.4-1968"
using default charset "UTF-8"
Default database being set to iBalekaDB
1>
Inside my freetds.conf file, I have this configuration set up:
# server specific section
[global]
# TDS protocol version
tds version = 8.0
text size = 20971520
client charset = UTF-8
dump file = /tmp/freetds.log
debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
[iBalekaServer]
host = xxxxxxxx.xxxxxxx.windows.net
port = 1433
tds version = 8.0
client charset = UTF-8
My db_connection.php file looks like this:
try {
$dataSource = "dblib:host=iBalekaServer;dbname=iBalekaDB;";
$username = "xxxxxxxxxxxx";
$password = "xxxxxxxxxxxx";
$connectionObject = new PDO($dataSource, $username, $password);
$connectionObject->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if ($connectionObject) {
echo "<h2>Connection Successful</h2>";
} else {
echo "Connection Error";
}
} catch (PDOException $e) {
echo $e->getMessage();
}
I ran tsql -C on the VPS and got this:
Compile-time settings (established with the "configure" script)
Version: freetds v0.91
freetds.conf directory: /etc/freetds
MS db-lib source compatibility: no
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes
I checked to see if I had pdo_dblib installed, and it was present when I ran phpinfo() on my Linux VPS Server.
What could be the issue here?
EDIT: using mssql_connect works. I really wanted to use PDO
On my test, I changed the $username to the format of UID (e.g. <username>#<db_server_name>), and it fixed your issue of SQLSTATE[01002] Adaptive Server connection failed (severity 9).
BTW, you can grab the UID from the connectionstring from Azure portal.
Additionally, if you get the issue of General SQL Server error: Check messages from the SQL Server (severity 16), you can refer to the answer of PDO DBLib not working.
Any update, please feel free to let me know.

Trouble With Connecting to MSSQL DB

I have an Ubuntu 12.04 server and I'm trying to establish a connection to a MSSQL database.
I've managed to connect using tsql and isql, but osql doesn't work and connecting with PHP using PDO also isn't working.. I will try to provide as much information as I can and if you need more just let me know and I will edit.
freetds.conf:
[MSSQL]
host = TPSACC
port = 54488
tds version = 8.0
odbc.ini:
[MSSQL]
Description = MS SQL connection to PRODUCTION database
Driver = FreeTDS
Database = PRODUCTION
Server = TPSACC
UserName = sa
Password = pass
Trace = No
TDS_Version = 8.0
Port = 54488
odbcinst.ini:
[FreeTDS]
Description = ODBC for Microsoft SQL
Driver = /usr/local/lib/libtdsodbc.so
UsageCount = 1
Threading = 2
~> isql MSSQL sa pass
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>
~> tsql -S MSSQL -U 'sa' -P 'pass'
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
1>
~> osql -S MSSQL -U sa -P pass
checking shared odbc libraries linked to isql for default directories...
strings: '': No such file
trying /tmp/sql ... no
trying /tmp/sql ... no
trying /etc ... OK
checking odbc.ini files
reading /home/toolplas/.odbc.ini
[MSSQL] not found in /home/toolplas/.odbc.ini
reading /etc/odbc.ini
[MSSQL] found in /etc/odbc.ini
found this section:
[MSSQL]
Description = MS SQL connection to PRODUCTION database
Driver = FreeTDS
Database = PRODUCTION
Server = TPSACC
UserName = sa
Password = pass
Trace = No
TDS_Version = 8.0
Port = 54488
looking for driver for DSN [MSSQL] in /etc/odbc.ini
found driver line: " Driver = FreeTDS"
driver "FreeTDS" found for [MSSQL] in odbc.ini
found driver named "FreeTDS"
"FreeTDS" is not an executable file
looking for entry named [FreeTDS] in /etc/odbcinst.ini
found driver line: " Driver = /usr/local/lib/libtdsodbc.so"
found driver /usr/local/lib/libtdsodbc.so for [FreeTDS] in odbcinst.ini
/usr/local/lib/libtdsodbc.so is an executable file
"Server" found, not using freetds.conf
Server is "TPSACC"
osql: no IP address found for "TPSACC"
In PHP I have:
$conn = new PDO ("dblib:host=TPSACC;dbname=PRODUCTION","$username","$pw");
..or..
$conn = new PDO ("dblib:host=TPSACC;port=54488;dbname=PRODUCTION","$username","$pw");
And they both return this error:
SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)
I have been stuck here for a couple days and can't quite figure out why only half of the connections actually work..
Any and all help is really appreciated, thanks!
EDIT: It is different than that question, I explained in a comment but will repost here:
For that one the problem was that the port was changed from 1433. Mine was also changed and I fixed that, the port is now 54488 and since that change tsql and isql have been working. However, it still doesn't solve the osql and PHP issues.
osql is choking on something in your configuration. osql is a debugging utility which simply checks out your configuration, then passes along to unixODBC's isql to connect (http://linux.die.net/man/1/osql). Try this for your odbc.ini:
[MSSQL]
Driver = FreeTDS
Description = MS SQL connection to PRODUCTION database
Server = tpsacc.yourfulldomain.com
Port = 54488
TDS_Version = 7.2
Database = PRODUCTION
UserName = sa
Password = pass
Trace = No
Also, are you sure that's the correct location for libtdsodbc.so? When I install freetds-dev with Ubuntu 14 x64 (utopic), it installs to /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so; example odbcinst.ini:
[FreeTDS]
Description = v0.91 with protocol v7.2
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
And for good measure, the typical freetds.conf I use:
# A typical Microsoft server
[MSSQL]
host = tpsacc.yourfulldomain.com
port = 54488
tds version = 7.2
FreeTDS only supports up to TDS version 7.2 with most languages. While using "8.0" shouldn't break anything, using 7.2 is better for consistency. If you need to check for reference, I have a Vagrant box with a full configuration available here, with examples: https://github.com/FlipperPA/django-python3-vagrant/ Good luck!

Connecting to MS SQL database with PHP: Data source name not found, and no default driver specified

I'm stuck with this problem for a while and I just can't get any further, I did a lot of searches but nothing works... I'm trying to connect to a Microsoft SQL Database with php using odbc.
Everything is set up, as follows (the values between "" are correct in the file):
/etc/odbc.ini:
[CRMCONNECT]
Description = "CRMConnect"
Driver = FreeTDS
Trace = No
Servername = CRMSERVER
Database = "dbname"
UserName = "username"
Password = "password"
[Default]
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
/etc/odbcinst.ini:
[FreeTDS]
Description = tdsodbc
Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/x86_64-linux-gnu/odbc/libtdsS.so
CPTimeout = 5
CPReuse = 5
FileUsage = 1
/etc/freetds/freetds.conf:
[CRMSERVER]
host = xxx.xxx.xxx.xxx
port = 1433
tds version = 8.0
I doublechecked the host many times and it is correct. I also tried tds version 7.0, but no luck.
I can succesfully connect to the server with isql:
root#crmart-web004:/# isql -v CRMCONNECT "user" "pass"
+---------------------------------------+
| Connected! |
| |
| sql-statement |
| help [tablename] |
| quit |
| |
+---------------------------------------+
SQL>
But with php I just can't get it working, I get the following error:
[unixODBC][Driver Manager]Data source name not found, and no default driver specified
My connectionstring:
$connection = odbc_connect("Driver={CRMCONNECT};Server=xxx.xxx.xxx.xxx;Database=dbname;","username","password");
All parameters are doublechecked and are correct.
How come I can successfully connect with isql but it fails in php?
My php version:
PHP Version 5.4.4-14+deb7u5
odbcinst configuration:
unixODBC 2.2.14
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
I hope someone has an idea what could be wrong.
Thanks in advance
Regards
UPDATE:
I changed my connectionstring to:
$connection = odbc_connect("CRMCONNECT;Database=dbname;","user","pass");
which is resulting in another error:
[unixODBC][Driver Manager]Driver's SQLAllocHandle on SQL_HANDLE_HENV failed
I'll be looking into that, thanks again vinodadhikary
Regards.
UPDATE 2:
My connection string was wrong, it should have been:
$connection = odbc_connect("CRMCONNECT","user","pass");
Thanks vinodadhikary!
Regards and happy holidays.
Since you already have CRMCONNECT DSN defined, you could use the following connection method:
$connection = odbc_connect("CRMCONNECT","username","password");
Also in your connection string you have Driver={CRMCONNECT};. CRMCONNECT as you've defined is not a driver, it is a Data Source Name. The driver in your case would be FreeTDS
I had the same error in Laravel 5.5 with PHP 7.1.9 on Debian 7.11. Fixed it by removing curly braces from driver's name in DSN:
Failed: "odbc:Driver={fail};Server=host;Database=db;"
Worked: "odbc:Driver=success;Server=host;Database=db;"
Another working option was moving data source configuration from this string into odbc.ini and then referencing it: "odbc:odbc_ini_data_source_name"
The funny thing is that the same data source with Driver={SQL Server} (with curly braces) worked correctly under Windows 10.
The same applies for PDO. $conn = new PDO("odbc:CRMCONNECT"); and be sure to set your default driver in odbc.ini
[Default]
Driver = IBM i Access ODBC Driver 64-bit in our case

Will I need to recompile/install php to add the mssql extension?

I have a system that is running php, and I recently needed to add connectivity to an MSSQL database. I have FreeTDS and UnixODBC installed/configured correctly, and I can make successful queries in python, and via utilities like tsql and isql. After looking at phpinfo() I've discovered I don't have a 'sqlsrv' section, and there is no mssql.so file in my php extensions directory.
I want to add this to my system without having to recompile/install php. Would I be able to find and download the mssql.so file, put it into my extensions directory, add extension=/path/to/mssql.so to my php.ini file, and reload apache to get this working? Or is there more steps I would need to take?
EDIT:
The system is running SLES11 with PHP 5.2
EDIT 2:
I've managed to get the php5-mssql extension installed. I grabbed the source, extracted it, and copies these files:
ext/mssql/config.m4
ext/mssql/php_mssql.c
ext/mssql/php_mssql.h
Then, in the directory where I copied the files to, I ran phpize (you will need to install php5-devel to get this tool), and compiled the extension like so:
./configure --with-mssql=/usr/local/freetds
make
I also had to add a line and comment out a line in php_mssql.c before it could actually compile correctly (not everyone will need to do this):
{NULL,NULL,NULL}
/*PHP_FE_END*/
This created the mssql.so file in /php_mssql/modules/ (relative to where I compiled the code), which I was able to move to my extensions directory (you can find this with php -i | grep extensions). I added extension=mssql.so to my php.ini file; however, there is still no 'sqlsrv section in phpinfo().
Some connection methods seem to partially work:
When running the following code from a shell, <h1>Connection Success</h1> is shown; but when opened in a browser, nothing after the mssql_connect line is shown:
<?php
//*************************************************************************
//Open Database Connection
//*************************************************************************
//phpinfo();
$dbserver="MyServer";
$dbusername="user";
$dbpassword="pass";
$defaultdb="DBName";
$cn = mssql_connect($dbserver,$dbusername,$dbpassword) or die("Connection Error");
$db = mssql_select_db($defaultdb,$cn) or die("Database Error");
echo "<h1>Connection Success</h1>";
?>
So it looks like I'm partially getting a connection that way? When I try with a PDO object, I get another error:
Code:
<?php
$con = new PDO('odbc:host=MyServer;dbname=DBName','user','pass');
?>
Error:
PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[IM002] SQLDriverConnect: 0 [unixODBC][Driver Manager]Data source name not found, and no default driver specified' in /path/to/php/file/test3.php:3
Stack trace:
#0 /path/to/php/file/test3.php(3): PDO->__construct('odbc:host=MySer...', 'user', 'pass')
#1 {main}
thrown in /path/to/php/file/test3.php on line 3
I've also tried the following (assuming that the PDO statement/DSN in the previous code was incorrrect):
<?php
try {
$db = new PDO("odbc:Driver=FreeTDS; Server=MyServer; Port=1433; Database=DBName; UID=user; PWD=pass;");
} catch (PDOException $exception) {
die("$exception");
}
echo "<h1>Success!</h1>";
?>
This showed <h1>Success!</h1> from the shell, but showed the following error in my web browser:
exception 'PDOException' with message 'SQLSTATE[08001] SQLDriverConnect: 0 [unixODBC][FreeTDS][SQL Server]Unable to connect to data source' in /path/to/php/file/test4.php:3 Stack trace: #0 /path/to/php/file/test4.php(3): PDO->__construct('odbc:Driver=Fre...') #1 {main}
In ODBC the error message contains elements in [] at the start of the message and the rightmost one is the part of the chain reporting the error (see ODBC Diagnostics & Error Status Codes. So, "[unixODBC][Driver Manager]Data source name not found, and no default driver specified" was reported by unixODBC. What unixODBC is saying is the string passed to the ODBC API SQLConnect or SQLDriverConnect does not identify a DSN (data source name) or an ODBC driver and there is no default DSN defined. You can find where your data sources are defined by running odbcinst -j e.g.,
$ odbcinst -j
unixODBC 2.2.14
DRIVERS............: /etc/odbcinst.ini
SYSTEM DATA SOURCES: /etc/odbc.ini
FILE DATA SOURCES..: /etc/ODBCDataSources
USER DATA SOURCES..: /home/martin/.odbc.ini
SQLULEN Size.......: 4
SQLLEN Size........: 4
SQLSETPOSIROW Size.: 2
Here, drivers are defined in /etc/odbcinst.ini, system data sources in /etc/odbc.ini and user data sources in /home/martin/.odbc.ini. As you'll probably be running PHP probably under a web server I'd stick to using the system data sources if I were you. You can list your system data sources with odbcinst -q -l -s. You find a a very good explanation of Linux/ODBC at Linux/UNIX ODBC.
Your second error "[unixODBC][FreeTDS][SQL Server]Unable to connect to data source" is reported by the SQL Server driver from FreeTDS so in this case you must have passed sufficient information to unixODBC to at least allow it to identify the driver, load it and call SQLConnect/SQLDriverConnect in it. You can see what was passed to unixODBC's SQLConnect/SQLDriverConnect by enabling tracing in unixODBC. You enable tracing of unixODBC by editing your odbcinst.ini file (locate with odbcinst -j command above) and adding the following to the top of it:
[ODBC]
Trace = yes
TraceFile = /tmp/unixodbc.log
Now, when you run your php example it will log to /tmp/unixodbc.log all ODBC API calls and the one you are looking for is SQLConnect or SQLDriverConnect. e.g., when I connect to a DSN called mydsn with a username and password of XXX and YYY I see:
[ODBC][31521][1374740062.012973][SQLDriverConnect.c][687]
Entry:
Connection = 0x9d7d430
Window Hdl = (nil)
Str In = [DSN=mydsn;UID=XXX;PWD=********][length = 29]
Str Out = 0xbfdeb83c
Str Out Max = 512
Str Out Ptr = 0xbfdeb638
Completion = 0
UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE'
DIAG [01000] [Easysoft][SQL Server Driver][SQL Server]Changed database context to 'master'.
DIAG [01000] [Easysoft][SQL Server Driver][SQL Server]Changed language setting to us_english.
Note, this connection was successful and it clearly shows part of the connection string was DSN=mydsn and mydsn exists as a DSN in my /etc/odbcinst.ini.
isql can work differently to some ODBC enabled applications as isql calls the ODBC API SQLConnect whereas most ODBC applications these days are ODBC 3 aware and use SQLDriverConnect. The main difference is SQLConnect is only given 3 arguments, a DSN name, a username and a password where SQLDriverConnect is given a single string of attribute/value pairs defining the connection. I only tell you this so you are aware how it is possible for isql to work and something else not to.
However, in your second case when you examine your trace you'll see unixODBC got something useful enough to identify the driver, load it and call freeTDS's ODBC driver and the error "Unable to connect to data source" is coming from freeTDS. So, I suggest your DSN is probably ok and your freetds.conf is incorrect in some way. As I don't use freeTDS myself I'm not sure but I've heard you can use ODBC with freeTDS without any reference to the freetds.conf file and switches based on whether you use Server or ServerName. I'm sure there are loads of examples on the freeTDS web site.
Here's how I connect to MS SQL servers from a LAMP (Ubuntu) stack:
/etc/odbc.ini
# Define a connection to a Microsoft SQL server
# The Description can be whatever we want it to be.
# The Driver value must match what we have defined in /etc/odbcinst.ini
# The Database name must be the name of the database this connection will connect to.
# The ServerName is the name we defined in /etc/freetds/freetds.conf
# The TDS_Version should match what we defined in /etc/freetds/freetds.conf
[mssql]
Description = MSSQL Server
Driver = freetds
Database = XXXXXX
ServerName = MSSQL
TDS_Version = 8.0
/etc/odbcinst.ini
# Define where to find the driver for the Free TDS connections.
[freetds]
Description = MS SQL database access with Free TDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1
/etc/freetds/freetds.conf
# The basics for defining a DSN (Data Source Name)
# [data_source_name]
# host = <hostname or IP address>
# port = <port number to connect to - probably 1433>
# tds version = <TDS version to use - probably 8.0>
# Define a connection to the Microsoft SQL Server
[mssql]
host = XXXXXX
port = 1433
tds version = 8.0
And here's the PHP code:
$con = new PDO('dblib:host=mssql;dbname=MyDB', 'domain\username', 'password');
You may need to tweak things a bit for your OS. To install the necessary software on Ubuntu I did something like this:
sudo apt-get install php5-odbc php5-sybase tdsodbc
Use PDO and instal this http://www.php.net/manual/en/ref.pdo-sqlsrv.php
I always use PDO it can easy do all the database interaction you need with different db drivers and the same php code. Except the query languages which is sometimes a little different.
For MSSQL you only need to add the drivers just paste the .dll's, add the entry to the conf.ini and restart apache.

Categories