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;";
Related
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.
I'm developing a web application with an AWS EC2 server (using php) to access a MS SQL Server database.
After a long search for solutions, I found this solution to use an ODBC driver. Fine, the development went well and I have no problems to connect to database or persist data.
But when I deployed my application, any action returns this error:
ERRO: IM001: [unixODBC][Driver Manager]Driver does not support this
function
I really tried all that I know and couldn't resolve this.
My EC2 configuration is:
yum install unixODBC unixODBC-devel freetds freetds-devel
And my odbc/freetds conf files are:
/etc/odbc.ini
[TDS_NAME]
Description = decription
Driver = TDS_NAME
Database = MY_DB
Servername = TDS_NAME
UID = VIPS
Port = 1433
TDS_Version= 7.3
/etc/odbcinst.ini
[TDS_NAME]
Description = TDS Connection
Driver64 = /usr/lib64/libtdsodbc.so
Setup64 = /usr/lib64/libtdsS.so
FileUsage = 1
UsageCount = 1
[ODBC]
Trace = yes
TraceFile /tmp/odbc.log
/etc/freetds.conf
[TDS_NAME]
host = MY_HOST
port = MY_PORT
tds version = 7.3
I run my queries using odbc_execute() or odbc_exec() and the error happens when my consult has some parameter. I'm pretty sure that the problem isn't my configuration files because I can connect successfully to the server and run a simple "SELECT * FROM table" and connect using isql running any query goes well.
Anyone can help me?
OBS: PHP RUNNING VERSION - PHP 5.6.10
A few things to consider:
What version of FreeTDS are you running?
What version of SQL Server are you running?
You need this to properly pick the correct TDS version. You're configured to use TDS 7.3, which would require FreeTDS 0.95 and SQL Server 2008. If you're just doing basic stuff, perhaps consider changing your TDS Version to 7.2 or 7.1?
Here's a handy chart of what features are supported by which TDS version in FreeTDS:
http://www.freetds.org/userguide/choosingtdsprotocol.htm
Good luck!
I'm attempting to connect to a SQL Azure database via PHP running on an Ubuntu 11.04 server.
The server is running PHP Version => 5.3.5-1ubuntu7.11.
I've installed freetds-bin, freetds-common, tdsodbc, odbcinst, php5-odbc and unixodbc using apt-get install multiple times. I attempted to compile FreeTDS with SSL support, but am not sure that was successful.
At this point, I receive an error "08S01 - Communication link failure" when attempting to connect using the isql tool. A Microsoft article explains the error as "The communication link between the driver and the data source to which the driver was attempting to connect failed before the SQLDriverConnect function completed processing." Some research on that specifically points to lack of SSL support in FreeTDS, but I'm unclear how to verify that has been enabled.
I will using either PHP Data Objects or mssql_* functions to connect to the SQL Azure database. I'm less familiar with PDO, but it seems that PDO does not necessarily use ODBC? I'm quite unclear on that, and I suspect it's leading me to troubleshoot problems seen by isql that are unrelated to the problems I'm seeing in PHP. Do connectivity problems with the isql tool relate to connectivity problems in either PDO or mssql_* functions in PHP?
My latest attempt, using PDO, is:
<?php
$c = new PDO("odbc:Driver=FreeTDS;Port=1433;Server=sssssssssss.database.windows.net;Database=db_xxxxx_xxx_xxx;UID=db_xxxxx_xxx_xxx_ExternalWriter;PWD=ppppppppp");
?>
This code generates the following errors in my Apache log file:
[Tue Dec 24 13:23:10 2013] [error] [client 10.1.1.11] PHP Fatal error:
Uncaught exception 'PDOException' with message 'SQLSTATE[08S01]
SQLDriverConnect: 20004 [unixODBC][FreeTDS][SQL Server]Read from the
server failed' in /var/www/test/pdo.php:3\nStack trace:\n#0
/var/www/test/pdo.php(3): PDO->__construct('odbc:Driver=Fre...')\n#1
{main}\n thrown in /var/www/test/pdo.php on line 3
My /etc/freetds/freetds.conf:
[global]
# TDS protocol version
tds version = 9.1
# Whether to write a TDSDUMP file for diagnostic purposes
# (setting this to /tmp is insecure on a multi-user system)
dump file = /tmp/freetds.log
debug flags = 0xffff
# Command and connection timeouts
; timeout = 10
; connect timeout = 10
# If you get out-of-memory errors, it may mean that your client
# is trying to allocate a huge buffer for a TEXT field.
# Try setting 'text size' to a more reasonable limit
text size = 64512
# A typical Microsoft server
[FreeTDS]
host = ssssssssss.database.windows.net
port = 1433
tds version = 9.1
client charset = UTF-8
/etc/odbc.ini:
[TS]
Description = "test"
Driver = FreeTDS
Server = sssssssssssss.database.windows.net
Port = 1433
Database = db_xxxxxxx_xxx_xxx
/etc/odbcinst.ini
[FreeTDS]
Description = tdsodbc
Driver = /usr/lib/odbc/libtdsodbc.so
Any help on this mess would be very appreciated. I'm clearly lost at this point. Thanks!
I've not tried it with Azure specifically, but on the local SQL Server machines we have here I found the php5-sybase module with PDO to be massively easier to live with than freetds:
apt-get install php5-sybase
<?php
$dsn = 'dblib:dbname=TestDB;host=sqlserver;charset=UTF-8';
$dbh = new PDO($dsn, 'username', 'password');
Also, when troubleshooting issues, I find looking at Wireshark traces of the DB traffic to be enlightening, as there are often very helpful messages emitted by SQL server that don't make it out in the PDO error.
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.
I have mysql on a linux server which I own having CentOS installed in it. I want to fetch data from another windows server having mssql database.
I need to create a php script that can get the values from mssql server and insert it into mysql server.
I have tried installing FreeTDS also PDO but still I am unable to connect (not sure if I have installed it properly). The error messages I get are Could not Connect to the server and drivers not found.
How can I check if I have installed freetds and PDO drivers correctly.
Basic Diagram of what I am trying to do:
Server A (Mumbai) {Linux Cent OS, FreeTDS and PDO installed} ---------> Server B (Delhi) {Windows, MSSql}
I want to get data from Server B to Server A.
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
62Error 20009 (severity 9):
Unable to connect: Adaptive Server is unavailable or does not exist
OS error 110, "Connection timed out"
There was a problem connecting to the server
root#server [~]# tsql -C
Compile-time settings (established with the "configure" script)
Version: freetds v0.91
freetds.conf directory: /usr/local/etc
MS db-lib source compatibility: no
Sybase binary compatibility: no
Thread safety: yes
iconv library: yes
TDS version: 5.0
iODBC: no
unixodbc: yes
SSPI "trusted" logins: no
Kerberos: no
How can I update TDS version form 5 to 7
Please guide.
Use ADODB Connection
$conn = new COM ("ADODB.Connection", NULL, CP_UTF8) or die("Cannot start ADO");
$connStr = "PROVIDER=SQLOLEDB;SERVER=myServer;UID=myUser;PWD=myPass;DATABASE=myDB";
$conn->open($connStr); //Open the connection to the database
$SQL="SELECT id, .........................";
$res=$conn->execute($SQL);
while (!$res->EOF) //carry on looping through while there are records
{
$id=$res->Fields('id')->value;
}
http://php.net/manual/en/class.com.php
Now go to Example #2 COM example (2)
Well, you can use the mssql select querys, set a variable in php with the result from the mssql query, and then do a mysql insert query to insert it into your database
$link = mssql_connect($server, 'sa', 'phpfi');
mssql_select_db('php', $link)
$query = mssql_query('SELECT [id] FROM [php].[dbo].[userlist]');
while ($row = mssql_fetch_assoc($query)) {
$row['id']
$con=mysqli_connect("127.0.0.1","root","pass","db");
mysqli_query($con,"INSERT INTO tablname VALUES('$id')");
}
Give this a try.
Of course you have to customize it to fit your needs.
Configure FreeTDS
This is a perfect tutorial for configuring FreeTDS. Every thing from basic..superb tutorial.
Thanks to Hugo Brown.