PDO: How to access Microsoft Access file on Linux? - php

I have managed to read data of Microsoft Access file (.accdb) on Windows using PDO but I'm having problem getting to work on Linux (CentOS). I can see modules is installed:
[root#rapid host]# php -m | grep PDO
PDO
PDO_ODBC
[root#rapid host]# php -m | grep odbc
odbc
code:
<?php
try{
$dbhAccess = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=/root/access/data.accdb;Uid=Admin");
}
catch(PDOException $e){
echo $e->getMessage();
exit();
}
I get an erro when I execute (CLI) PHP file:
[root#rapid host]# php access.php
SQLSTATE[IM002] SQLDriverConnect: 0 [unixODBC][Driver Manager]Data source name not found, and no default driver specified

you should install the MDB driver.
I have no way to try it now, but I think that MDB Tools (specifically the ODBC driver) can do what you' re interested to.

I've never worked with a Microsoft Access database but I do regularly connect to DB2 (on IBM AS/400's) and MS SQL servers from Linux (Ubuntu) servers. Your error seems to indicate you don't have a MS Access driver installed - the only one I'm aware of is: http://www.easysoft.com/products/data_access/odbc-access-driver/index.html
Your error message also says the "Data source name not found" - in order for me to connect to DB2 or MSSQL I have to add some information to /etc/odbc.ini and /etc/odbcinst.ini.
/etc/odbcinst.ini - this is where you describe where to find the drivers for ODBC. Here's an example of what I use for DB2 and MSSQL:
[iseries]
Description = iSeries Access for Linux ODBC Driver
Driver = /usr/lib/libcwbodbc.so
Setup = /usr/lib/libcwbodbcs.so
NOTE1 = If using unixODBC 2.2.11 or later and you want the 32 and 64-bit ODBC drivers to share DSN's,
NOTE2 = the following Driver64/Setup64 keywords will provide that support.
Driver64 = /usr/lib/lib64/libcwbodbc.so
Setup64 = /usr/lib/lib64/libcwbodbcs.so
Threading = 2
DontDLClose = 1
UsageCount = 1
# 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
[ODBC]
Trace = no
TraceFile = /tmp/odbc.log
In that last section ([ODBC]) I currently have Trace = no - if you change that to Trace = yes you will get some helpful debugging information in the /tmp/odbc.log file.
/etc/odbc.ini - this is where you define your data sources. Here's an example of what I use for DB2 and MSSQL:
[primary]
Description = primary
Driver = iseries
System = XXX.XXX.XXX.XXX
UserID = XXXXXXXXXX
Password = XXXXXXXXXX
Naming = 0
DefaultLibraries = QGPL
Database = MYLIB
ConnectionType = 0
CommitMode = 2
ExtendedDynamic = 0
DefaultPkgLibrary = QGPL
DefaultPackage = A/DEFAULT(IBM),2,0,1,0,512
AllowDataCompression = 1
LibraryView = 0
AllowUnsupportedChar = 0
ForceTranslation = 0
Trace = 0
# Define a connection to the MSSQL 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 = MyDatabase
ServerName = mssql
TDS_Version = 8.0
I've seen a number of questions here on StackOverflow talking about using MSFT Access databases from a Linux machine - and there doesn't seem to ever be a happy ending. If there is any way you can port the data to a different, better supported, database system (like MySQL) I think you'll save yourself some headaches. Good luck!

You can not use {Microsoft Access Driver (*.mdb, *.accdb)} as part of your data source because Microsoft do not make an MS Access ODBC driver for Linux. There are 2 ODBC drivers for MS Access as far as I know of. The MDB Tools and the Easysoft ODBC-Access Driver.
If you install either driver you can either use a DSN which you setup in your odbc.ini file or as you prefer a DSN-Less connection. Here is an example of the an Easysoft DSN-Less connection to an MS Access database
PDO("odbc:Driver={Driver=Easysoft ODBC-ACCESS};Dbq=/root/access/data.accdb");
More information on connecting and getting data back using PDO-ODBC can be found on Easysoft PHP guide There is a section about half way down that talks about PDO-ODBC.

import pandas_access as mdb
db_filename = 'my_db.mdb'
# Listing the tables
for tbl in mdb.list_tables(db_filename):
print(tbl)
# Read a small table
df = mdb.read_table(db_filename, "MyTable")
On Ubuntu you may need to run:
sudo apt install mdbtools

For WINDOWS this is the solution.
After investing a lot of time I have the solution.
The 32-bit version of "AccessDatabaseEngine" must be installed.
Download the 32-bit Access Engine on: https://www.microsoft.com/es-es/download/confirmation.aspx?id=13255
And run it with the command line: AccessDatabaseEngine.exe /passive
After that, it should work.

Related

AWS EC2 linux + PHP + ODBC + Remote MS SQL Server

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!

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!

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.

PHP OSX ODBC + MS SQL

Hi 2 days I trying setup PHP + MSSQL under OS X 10.8.2 server but no success yet.
I have tried install FreeTDS, compiling mssql.so, successfully loaded it with PHP,
but function mssql_connect(server,user,pass); always return false.
also I tried using standart ODBC Administrator to configure drivers settings,
my odbc.ini looks like this:
[ODBC]
Trace = 1
[ODBC Data Sources]
MSSQL = MSSQL
[MSSQL]
Driver = /usr/local/lib/libodbc.2.dylib
Description = MSSQL
username = su
password = 1234
but no success with odbc_connect();
also tried DSN less method
<?php
$connection = odbc_connect( 'DRIVER={MSSQL};SERVER=192.168.1.94\SQLEXPRESS;DATABASE=NMSDb', 'sa', '1234' ) or die('Error')
?>
I can successfully connect to SQL from Navicat using host 192.168.1.94\SQLEXPRESS, user sa and password 1234
but how do this from php? usually I use MySQL there is no problem with that, but MS SQL is nightmare

How can I connect to Sql Server from a Mac with PHP PDO?

If you search Google for this question, you will find a lot of incorrect, misleading, and outdated information. Surprisingly, there isn't a solid answer on Stack Overflow, so we should change that.
I am using the Mac port installation of Apache and PHP. I have installed php5-mssql, and I can see mssql on my phpinfo() page.
But I don't see it listed under PDO.
PDO support enabled
PDO drivers dblib, mysql, odbc, pgsql
Is mssql not associated with PDO? Is there another driver that can be used on a Mac to connect to a SqlServer database using PDO? Seems like this is something that should be possible.
Does this help you?
http://blog.nguyenvq.com/2010/05/16/freetds-unixodbc-rodbc-r/
I use FreeTDS to connect to Microsoft SQL servers from a Linux server and it looks like the person in the link above has used FreeTDS to connect from a Mac.
Here is my /etc/freetds/freetds.conf file (the only part I added was at the very end for the XYZ server):
[global]
# TDS protocol version
; tds version = 4.2
# 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
# Define a connection to the MSSQL server.
[xyz]
host = xyz
port = 1433
tds version = 8.0
[Edit by the asker]
FreeTDS configuration is the first half of the answer. Once it's configured you should be able to run something like this from the command line and connect:
tsql -S xyz -U username -P password
Then you need to use dblib, not mssql, as the PDO driver:
$pdo = new PDO("dblib:host=$dbhost;dbname=$dbname",
"$dbuser","$dbpwd");
Where $dbhost is the name from the freetds.conf file
After looking at many threads, I've found that the best way to connect to MSSQL from Mac OS X with PHP 7 or older is to use dblib. (Just download the correct php version)
You can follow these instructions (ignoring the mssql.so extension) to connect very easily:
https://github.com/BellevueCollege/public-docs/blob/master/PHP/configure-mssql-pdodblib-mac.md
It worked perfect with OS X El Capitan, Bitnami with PHP 7.
Steps
1.- Install XCode
$ xcode-select ---install
2.- Install Homebrew
3.- Install autoconf using Homebrew.
$ brew install autoconf
4.- Install FreeTDS
$ brew install freetds
5.- Download your version of PHP Source and uncompress it.
6.- Build the PDO DBLIB extension (Example for PHP 5.5.14)
$ cd php-5.5.14/ext/pdo_dblib
$ phpize
$ ./configure --with-php-config=/usr/bin/php-config --with-pdo-dblib=/usr/local/
$ make
$ sudo cp modules/pdo_dblib.so /usr/lib/php/extensions/no-debug-non-zts-20121212
7.- Add the .so extensio to php.ini
extension=pdo_dblib.so
8.- Restart Apache
9.- Connect using the dblib dsn:
$pdo = new PDO("dblib:host=$dbhost;dbname=$dbname","$dbuser","$dbpwd");
dblib is the driver that need to be used with mssql on unix systems
No need for you to install anything else,
<?php
$dsn = 'dblib:dbname=testdb;host=127.0.0.1';
$user = 'dbuser';
$password = 'dbpass';
$dbh = new PDO($dsn, $user, $password);
Thanks Esteban for the nice guide (https://stackoverflow.com/a/37707426) which succesfully helped me install the pdo_dblib driver.
However, I was having issues connecting to my Azure SQL database from OSX 10 with PHP (5.5) and FreeTDS using the provided dblib dsn. What finally fixed it for me was appending the Azure database (m53man42a) to my username.
My dblib PDO connection in PHP:
$conn = new PDO("dblib:host=azure-sql;dbname=my-database-name",
"username#m53man42a",
"my-secret-password");
My FreeTDS.conf:
[azure-sql]
host = m53man42a.database.windows.net
port = 1433
tds version = 8.0
client charset = UTF-8
text size = 20971520
Consider adding this as a bullet number 10 in your list... :D
Note that Microsoft have published a PHP7 extension for this, but if you're still on PHP5.x, that doesn't help you. I've succeeded in connecting using a different stack: freetds,odbc,pdo.
I'm using OS X 10.11.6 (El Capitan) with Macports, PHP5.6.
I've started by creating an Azure SQL Database called mydb on a server with a name of myserver.database.windows.net. It's important to remember to open the firewall to your client IP address, which you do on the server.
First step is to install freetds with the ODBC driver, and its PHP connector (change php56 to the correct version of your PHP):
sudo port install freetds +odbc
sudo port install php56-odbc
Next, you need to include some lines in your configuration files:
/opt/local/etc/odbcinst.ini
[FreeTDS]
Description = ODBC for FreeTDS
Driver = /opt/local/lib/libtdsodbc.so
Setup = /opt/local/lib/libtdsodbc.so
FileUsage = 1
This tells the odbc library where to find its odbc driver.
/opt/local/etc/freetds/freetds.conf
[myserver]
host = myserver.database.windows.net
port = 1433
tds version = 7.0
This tells the freetdc library where to find your server.
/opt/local/etc/odbc.ini
[myds]
Description = Test for SQL Server on Azure
Driver = FreeTDS
Trace = Yes
TraceFile = /var/log/sql.log
Database = mydb
Servername = myserver
UserName = myusername
Password = mypassword
Port = 1433
Protocol = 7.0
ReadOnly = No
RowVersioning = No
ShowSystemTables = No
ShowOidColumn = No
FakeOidIndex = No
This creates a data source called myds pointing at your database, enabling you to connect with the following PHP:
$conn = new PDO('odbc:myds', 'myusername', 'mypassword');
If any of this doesn't work for you, first check that the freetds installation is correct using:
tsql -S myserver -U myusername -P mypassword
And then check that the ODBC specifications are OK using:
isql -v myds myusername mypassword
Thanks to https://github.com/lionheart/django-pyodbc/wiki/Mac-setup-to-connect-to-a-MS-SQL-Server, which does the equivalent job for Python and which pointed me in the right direction for all this.

Categories