mysql communicate with mssql on different server via php - php

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.

Related

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.

Pdo Dblib Mssql Connection Error

I am using my sync system for 2 years. And i didn't change anything. wierdly today sync system is broken. And i recieved an error message.
Connection failed: SQLSTATE[01002] Adaptive Server connection failed (severity 9)
I google it.
And i learned it about freetds version problem.
For checking it
I wrote this line in ssh
TDSVER=7.0 tsql -H 78.***.***.49 -p 1433 -U DBNAME
I recieved this message.
locale is "tr_TR.UTF-8"
locale charset is "UTF-8"
using default charset "UTF-8"
Msg 18456 (severity 14, state 1) from *****SERVER Line 1:
"Login failed for user 'DBNAME'."
Error 20002 (severity 9):
Adaptive Server connection failed
There was a problem connecting to the server
Same mistake.
I'm using dblib for connection via pdo.
What should i do ? What is the problem ?
UPDATE:
I read this part in php manuel
"If it is not possible to use SqlSrv, you can use the PDO_ODBC driver to connect to Microsoft SQL Server and Sybase databases, as the native Windows DB-LIB is ancient, thread un-safe and no longer supported by Microsoft."
My Free Tds Settings
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
It is ridiculous. But i found the problem.
"enforce password expiration" was on. And windows forces to change db password. When i disabled it, we solved the problem.

MSSQL VIA FreeTDS, ODBC, and Cpanel Unknown host machine name (severity 2)

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

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;";

php5 odbc_connect() function error when connecting to Visual FoxPro9 table

I'm running php5 on Ubuntu10.10 server where the unixODBC and php5-odbc packages have already been installed. I keep getting an error during the connection process - code:
$data_source = 'DRIVER={Microsoft dBASE Driver (*.dbf)};Data Source=//128.251.xxx.xxx/lv_apps/AppsLON/CData/dbf/cdma';"", "");
$conn = odbc_connect($data_source, "", "");
if (!$conn)
exit("Connection Failed: " .$conn );
error message:
1 Warning: odbc_connect(): SQL error: [unixODBC][Driver Manager]Data source name not found, and no default driver specified, SQL state IM002 in SQLConnect in /var/www/vfptest.php on line 6
I added extention=dbase.so and extention=odbc.so to both files: /etc/php5/apache2/php.ini and /etc/php5/cli/php.ini and re-compiled the php install with:
sudo ./configure --prefix=/usr --enable-dbase=shared --with-unixODBC
I've also gone to unixODBC and pecl to install the unixODBC and dbase libraries separately with no luck.
Also I found this link: http://www.devlist.com/ConnectionStringsPage.aspx
where it is stated that in order to create an ODBC connection to a foxpro database I use the line:
Driver={Microsoft Visual FoxPro Driver};SourceType=DBC;SourceDB=c:\demo.dbc;Exclusive=No;NULL=NO;Collate=Machine;BACKGROUNDFETCH=NO;DELETED=NO
this still did not work for me however; probably because I do not have the visual foxpro driver installed or my odbc.ini file pointing to the driver path...but I don't know.
In short - odbc_connect() takes; an ODBC Data Source Name (DSN), Username & Password as per --
http://php.net/manual/en/function.odbc-connect.php
As far as I am aware there is no VFP ODBC driver for Linux so you will, most likely, need to employ an ODBC Bridge solution like -
http://uda.openlinksw.com/odbc-odbc-mt/
This has a client/server architecture --
Linux client --
php ODBC Application
OpenLink Generic ODBC Driver (thin multi-tier ODBC client)
Windows server --
OpenLink Request Broker (Multi-tier server)
OpenLInk Agent for ODBC (Multi-tier server)
Fox Pro ODBC DSN (pre configured)
Fox Pro files...
I hope this helps?
Check out the very bottom of this thread on the MSDN network
the driver line you have posted is "...an ODBC connection string which is not supported for VFP tables having a version later than 6."
Although not familiar with linux connecting to VFP, however, odbc connections for such VFP connect to a PATH, not a specific table. Once the connection to the PATH is valid, THEN you can query any .DBF table IN that location.
Although I can't answer your specific connection info, I've found this link
http://www.phpfreaks.com/forums/index.php?topic=296832.0
that shows connecting to a datasource... notice its identifying the 'DRIVER={Microsoft dBASE Driver (*.dbf)};datasource=/home/dir/file.dbf;' used... You'll probably have to hit a combination of this driver and pathing info (I'd still try WITHOUT the specific .dbf file first).
Hope this helps..

Categories