通过PDO ODBC将PHP连接到MSSQL
当我执行此代码时:
print_r(PDO::getAvailableDrivers());
它说我有odbc
可用的驱动程序。
Array ( [0] => mysql [1] => odbc [2] => sqlite )
但是,当我尝试像这样使用它时:
$handle = new PDO("odbc:Server=dbServerIpAddress,myportnumber;Database=mydatabase", "myusername", 'mypassword');
它什么也没做-没有错误,也根本不起作用。它甚至不会执行到该行!
如何通过PDO和ODBC将PHP连接到此MSSQL数据库?
回答:
您需要设置几个配置文件。/etc/odbc.ini
,/etc/odbcinst.ini
而/etc/freetds/freetds.conf
(这些位置是有效的Ubuntu
12.04,并可能是正确的大多数* nixes)。
您需要安装unixodbc
和freetds
(不确定CentOS上的软件包名称是什么)。在Ubuntu中将是apt-get install
unixodbc tdsodbc。
# 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 = 7.1
/etc/odbcinst.ini
# Define where to find the driver for the Free TDS connections.# Make sure you use the right driver (32-bit or 64-bit).
[freetds]
Description = MS SQL database access with Free TDS
Driver = /usr/lib/i386-linux-gnu/odbc/libtdsodbc.so
#Driver = /usr/lib/x86_64-linux-gnu/odbc/libtdsodbc.so
Setup = /usr/lib/i386-linux-gnu/odbc/libtdsS.so
UsageCount = 1
/etc/freetds/freetds.conf(或者您可以在/etc/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 = 7.1
您可能必须tds version = 7.1
根据您的MSSQL版本更改上面的行。
在您的PHP代码中,您将如下创建PDO对象:
$pdo = new PDO("dblib:host=mssql;dbname=$dbname", "$dbuser","$dbpwd");
请注意,您的用户名可能需要采用以下格式:domain\username
。
另外,如果您phpinfo()
在页面中执行并搜索“ freetds”,它将显示一个mssql部分,其中freetds列为“库版本” ,您将知道它起作用。
以上是 通过PDO ODBC将PHP连接到MSSQL 的全部内容, 来源链接: utcz.com/qa/407156.html