The last 2 days I've spent a lot of time trying to figure out how to connect to MS SQL server hosted on Azure using PHP from an Ubuntu 14.04 server.
The code responsible to initiate the connection to the remote database is the following:
public function connect()
{
try
{
$this->databaseConnection = new \PDO(
'dblib:host='.$this->hostname.':'.$this->port.';dbname='.$this->databaseName.';',
$this->username,
$this->password
);
$this->databaseConnection->setAttribute(
\PDO::ATTR_ERRMODE,
\PDO::ERRMODE_EXCEPTION
);
}
catch (\PDOException $e)
{
throw new \Exception('Failed to connect to the database: '.$e->getMessage());
}
}
And every time I try to connect I receive:
Failed to connect to the database: SQLSTATE[01002] Adaptive Server connection failed (severity 9)
The problem is that this is a very general error and there's no way for me to understand what's causing the issue.
This is my /etc/freetds.conf configuration:
[placeholder.database.windows.net]
host = placeholder.database.windows.net
port = 1433
tds version = 7.2
client charset = UTF-8
And this is the tsql -C output:
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
In addition to this, I tried making some test using mssql_* functions and even if I was able to successfully connect to the database most of the queries didn't work.
For a simple solution for one sqlsrv server connection in your application, you can modify the tds version to 8.0 under the [global] section of the freetds.conf, e.g.
[global]
tds version = 8.0
Then test in PHP script:
try {
$pdo = new PDO("dblib:host=<azure_sql_name>.database.windows.net;dbname=<dbname>", "<username>", "<password>");
} catch (PDOException $e) {
echo "Error: " . $e->getMessage() . "\n";
}
It works fine on my side after the modification. Any further concern, please feel free to let me know.
The problem was caused by 2 different issues.
The first one was related to a wrong FreeTDS configuration. The freetds.con global section needs to be like this:
[global]
tds version = 8.0
The second one was caused by the fact that the username must be specified in the following way when connecting to a MSSQL server hosted on Azure:
<username>#<freeTDSServerName>
Where the specific server configuration in freetds.conf looks something like this:
[<freeTDSServerName>]
database = <databaseName>
host = <serverName>.database.windows.net
port = 1433
tds version = 8.0
So the PHP DB connection will look like something like this:
$this->databaseConnection = new \PDO(
'dblib:host='.$this->hostname.':'.$this->port.';dbname='.$this->databaseName.';',
$this->username.'#<freeTDSName>',
$this->password
);
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 have a SQL server 2008 R2 (running on Windows server 2008 64bit), which I'm trying to connect from PHP
My PHP server configuration:
CentOS 6.6
PHP 5.5.24 (compiled --with-mssql=/usr/local/freetds --with-pdo-dblib=/usr/local/freetds)
Apache 2.4.12
SELinux is disabled (according to this solution: PDO DBLIB accessing SQL Server 2008 and 2012)
I wrote the following PHP code to connect to the SQL server:
try {
require "classes/mypdo.class.php";
$pdo = new MyPDO('dblib:dbname=myDB;host=myServer', 'myUser', 'myPassword');
$pdo->debug = true;
} catch (PDOException $e) {
die("Connection failed: {$e->getMessage()}");
}
The connection failed with an error:
Connection failed: SQLSTATE[HY000] Unknown host machine name (severity 2)
I tried other DSN syntaxes like:
$pdo = new MyPDO('dblib:host=192.168.0.10', 'myUser', 'myPassword');
$pdo = new MyPDO('dblib:host=192.168.0.10:1433', 'myUser', 'myPassword');
$pdo = new MyPDO('dblib:host=myServer', 'myUser', 'myPassword');
and many other variations...
When I use an IP address instead of DSN the error is:
Connection failed: SQLSTATE[HY000] Unable to connect: Adaptive Server is unavailable or does not exist (severity 9)
/etc/freetds.conf
[global]
tds version = 7.1
dump file = /tmp/freetds.log
timeout = 10
connect timeout = 10
text size = 64512
client charset = UTF-8
[myServer]
host = 192.168.0.10
port = 1433
tds version = 7.1
I suspect that PHP ignoring freetds.conf (can't confirm it).
When I use tsql the connection is working.
tsql -S myServer -U MyUser -P MyPassword
locale is "en_US.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
1>
What is the reason that PHP refusing to connect to the SQL server?
There are sometimes problems with an setting inside php.ini
Please try to change:
mssql.secure_connection = Off
to
mssql.secure_connection = On
I have installed FreeTDS 0.91, ODBC, on a Cpanel server running Centos 6.5x64. Everything appears to be running fine and I can connect to the remote MSSQL 2012 server using:
/usr/local/freetds/bin/tsql -S sqlserver -U test -P mypassword
and succesfully execute queries in the database.
I can also connect through:
isql -v sqlserverdatasource test mypasswordhere
But for some reason /usr/local/freetds/bin/tsql -LH server.ip.here
returns no information or errors which doesn't make much sense when it is proven I can connect with the other methods above.
So now when running a test script from a cpanel account on the machine I get:
Unknown host machine name (severity 2)
Here is the test script:
//Database connection function.
function getConnection() {
try {
//$dbconnect = new PDO("sqlserver:Server=server.ip.here,1433;Database=dbname", "user", "password");
$dbconnect = new PDO("dblib:host=server.ip.here,1433;dbname=dbname", 'user', 'password');
} catch (PDOException $e) {
echo "CONNECTION ERROR.<br>Error message:<br><br>" . $e->getMessage();
die();
}
if (!$dbconnect) {
die('Cant connect to database. Please try again later!');
}
else{
echo "i'm in!";
return $dbconnect;
}
}
The first commented line is the old one using sqlserv which I found did not work at all from what i can tell because of the x64 OS. I have also tried with "" around user and pass as well as no marks at all.
php -m does show PDO and pdo-dblib.
Any ideas where I can look next?
Update: This was fixed. I missed in freetds.conf:
[global]
# TDS protocol version
tds version = 8.0
It was originally set to 4.5 instead of 8.
The fix for me was with three steps:
First, I edited /etc/freetds/freetds.conf and changed the tds version like this:
tds version = 8.0
The second step was not entering port number. The port was already 1433, and not specifying it fixed the exact same issue on my case.
Lastly, to connect properly, I had to restart networking as #user1054844 mentioned as this:
/etc/init.d/networking restart
After all these steps, I was able to connect and work with the SQL Server database.
You actually did not need ODBC at all since your connect script is using pdo_dblib not odbc. You can just install FreeTDS than enable pdo_dblib via the compile time flag in rawopts and rebuild via EasyApache. Of course cPanel specifics for this are a bit different.
I just did this for a friend and decided to document it since it is hard to find accurate clear information for FreeTds and pdo_dblib on cPanel.
Guide is here: FreeTDS And pDO_dblib On cPanel
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.
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 ;)