PDO dblib cannot connect with ip address as "host" parameter - php

I am trying to connect to a mssql db with dblib using the IP of the server as the host in the DSN.
With tsql, this works without any problem
$ tsql -S 192.168.56.101 -U .\user -P user
but in PHP this does not work.
$pdo = new PDO("dblib:host=192.168.56.101,1433;dbname=OtherC", '.\user', 'user');
The error I get is :
Error : SQLSTATE[01002] Adaptive Server connection failed (severity 9)

Check these:
port separator is "," on windows and ":" on linux/Mac
I never saw username as '.\user' but 'user'
locate freetds.conf on your disk. It is possible it exists in several places and tsql uses one while PHP used another one. Best is to symlink them into one common file and test on that. Note that a common place for that file is ~/.freetds.conf beside /etc/ or /usr/local/etc/
there should be a [global] section on your freetds.conf file. Put there these lines :
tds version = 8.0
text size = 20971520
client charset = UTF-8

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?

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

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');
}
?>

How to query in a specific database on Azure?

I'm trying to execute a (very) simple query on Azure MSSql Server using PHP, but it does not work and prints the follow message:
Warning: mssql_query(): message: Invalid object name 'MyTable'.
(severity 16)
I believe that the underlying driver is connecting directly the master database and that's why my objects are not available. So the obvious solution could be mssql_select_db() function, but it raises the follow error message:
Warning: mssql_select_db(): message: USE statement is not supported to
switch between databases. Use a new connection to connect to a
different Database. (severity 16)
So, any of you guys have ever queried successfuly the MS Azure SqlServer using PHP?
Aditional info:
1 - The connection appears to be OK, with no errors.
2 - I can't qualify/prefix my objects with database.schema, otherwise Azure says:
Warning: mssql_query(): message: Reference to database and/or server
name in 'myDatabase.dbo.MyTable' is not supported in this version of
SQL Server. (severity 15)
The General config is:
- CentOS
- PHP 5.3.3
- FreeTDS
- Apache 2
/etc/freetds.conf relevant part is like follows:
[global]
#TDS protocol version
; tds version = 4.2
[MyServerAtAzure]
host = mydatabase.database.windows.net
port = 1433
tds version = 8.0
database = MyDatabase
client_charset = UTF-8
The tsql output's:
# tsql -C
Compile-time settings (established with the "configure" script)
Version: freetds v0.91
freetds.conf directory: /etc
MS db-lib source compatibility: yes
Sybase binary compatibility: yes
Thread safety: yes
iconv library: yes
TDS version: 4.2
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: yes
And finally, the PHP code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
# Older FreeTDS installations need the FREETDSCONF Environment variable
putenv('FREETDSCONF=/etc/freetds.conf');
# Current release of FreeTDS uses the FREETDS environment variable. So we set both to be sure
putenv('FREETDS=/etc/freetds.conf');
$link = mssql_connect('MyServerAtAzure', 'user#mydatabase', 'password');
if ( !$link ) die('<br>Oops! CannotConnect');
//mssql_select_db('MyDatabase', $link); # FAILS because you can't use "USE" statement
$sql = "SELECT * FROM dbo.MyTable";
$rs = mssql_query($sql, $link);
?>
The previous resources that I've already visited are:
-
why-is-my-sql-server-query-failing
use-statement-is-not-supported-to-switch-between-databases-when-running-query
PHPFreaks
You can't perform cross-database queries and, like the error message says, you also can't change database context using USE. If you want to query from multiple Azure databases, you need to connect to them independently with different connection strings.
Also, did you try specifying the database explicitly (and not connecting to [...].wondows.net:
[MyServerAtAzure]
host = mydatabase.database.windows.net
port = 1433
Database = myDatabase
tds version = 8.0
client_charset = UTF-8
And also properly prefixing your table with its schema?
$sql = "SELECT * FROM dbo.MyTable;";

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.

Can not connect to SQL SERVER Using Latest Drivers for PHP

I have been trying to figure out which dll and how to use it to connect to sql server.
It was much easier using the old php_mssql.
I am using Xampp on WinXP Pro SP3. I have been unable to figure out how to connect, i have search the manual, and none of the command's work.
I get PDO Error Driver Not Found
extension-php_pdo_sqlsrv_54_ts.dll
extension=php_sqlsrv_54_ts.dll
I realized that I must use the SQLSERV 2.0 Drivers. But which dll is the correct one? And what syntax must I use to connect and run queries?
Thank you.
One way of doing this is using FreeTDS for Windows
I am assuming you have PHP >5.3
Download this http://download.moodle.org/download.php/dblib/php53/DBLIB_TS.zip
Add this line to your php.ini extension=php_dblib.dll
You will also need to make a file called freetds.conf in the root directory of your PHP installation.
It should look something like this:
[global]
host = xxx.xxx.xxx.xxx (host name or ip of the MSSQL server)
port = 1433
client charset = UTF-8
tds version = 8.0
text size = 20971520
Restart Apache and try running this script:
<?php
$link = mssql_connect('localhost', 'db_user', 'db_password');
if(!$link) {
echo'Could not connect';
die('Could not connect: ' . mssql_error());
}
echo'Successful connection';
mssql_close($link);
?>
hit me up on fb if this does not work ;)

Categories