Eric Z Beard Eric Z Beard - 1 year ago 136
PHP Question

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.

Answer Source

Does this help you?

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):

        # 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.
        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",

Where $dbhost is the name from the freetds.conf file