Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to SQL Server through PDO using SQL Server Driver

I am trying to connect to an existing SQL Server database using PDO with the drivers provided by Microsoft.

I have seen examples using odbc, dblib, mssql, etc., however I believe the connection string with these drivers should use 'sqlsrv'?

Are there any good examples of how to properly do this? If I should be doing this via some other method please let me know. Thanks!

like image 456
Drew Avatar asked Oct 05 '12 13:10

Drew


People also ask

How do I connect to a SQL Server connection?

Start the SQL Server, in the dialog window for the Server name enters the name of the instance that you want to connect with. From the Authentication drop down box, select the SQL Server Authentication and for the field Login and the Password enter your credentials then click the Connect button.

What is Pdo_dblib?

PDO_DBLIB is a driver that implements the PHP Data Objects (PDO) interface to enable access from PHP to Microsoft SQL Server and Sybase databases through the FreeTDS library. This extension is not available anymore on Windows.

What is FreeTDS driver?

FreeTDS is a set of libraries for Unix and Linux that allows your programs to natively talk to Microsoft SQL Server and Sybase databases. Technically speaking, FreeTDS is an open source implementation of the TDS (Tabular Data Stream) protocol used by these databases for their own clients.


2 Answers

Well that's the best part about PDOs is that it's pretty easy to access any database. Provided you have installed those drivers, you should be able to just do:

$db = new PDO("sqlsrv:Server=YouAddress;Database=YourDatabase", "Username", "Password"); 
like image 57
MatthewMcGovern Avatar answered Oct 02 '22 15:10

MatthewMcGovern


Mind you that in my experience and also of other (PHP - Why is new SQLSRV driver slower than the old mssql driver?) that using PDO_SQLSRV is way slower than through PDO_ODBC.

If you want to use the faster PDO_ODBC you can use:

//use any of these or check exact MSSQL ODBC drivername in "ODBC Data Source Administrator" $mssqldriver = '{SQL Server}';  $mssqldriver = '{SQL Server Native Client 11.0}'; $mssqldriver = '{ODBC Driver 11 for SQL Server}';  $hostname='127.0.0.1'; $dbname='test'; $username='user'; $password='pw'; $dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password); 
like image 30
Jan Avatar answered Oct 02 '22 14:10

Jan