LAMP之路

不积跬步,无以至千里!

php5.3远程连接mssql2005数据库

2014-4-12 一抹阳光 环境架设

php5.3开始php官方不再支持mssql,之前写的《windows下php5.2连接mssql2005数据库》已经不再适用。

经过苦苦查阅资料,终于成功。

以下步骤是在《windows2003+IIS6+php5.3+mysql5.5环境架设详细教程》环境上增加mssql支持。

1、连接Sql server 2005以上版本的sql server(如sql server 2005),需要在机器上先安装 SQL Server Native Client :官方下载

备用下载:sqlncli.zip

For sql server 2008R2:

官方下载  备用地址:sqlncli_for sqlserver2008R2.zip


2、先到微软网站下载 SQL Server Driver for PHP。备用下载:SQLSRV20.zip

 这是一个自解压的EXE文件,解压缩后你会得到以下文件:

QQ截图20140412224442.gif

其中的52、53表示就是php的5.2.x和5.3.x 版本,选择跟你php版本相匹配的;

将php_sqlsrv_53_nts_vc9.dll复制到php的ext目录中,并在php.ini中添加 extension=php_sqlsrv_53_nts_vc9.dll   接下来重新启动IIS 并运行phpinfo.php,来查看phpinfo的配置信息,如果看到下图信息,则说明可添加成功。

QQ截图20140412223425.gif



附用法函数:http://www.php.net/manual/zh/ref.sqlsrv.php

片段示例:

$connectionInfo =  array("UID"=>$username,"PWD"=>$password,"Database"=>$dbname);
$con = sqlsrv_connect($host,$connectionInfo);
if( $con ) {
     echo "Connection established.<br />";
}else{
     echo "Connection could not be established.<br />";
     die( print_r( sqlsrv_errors(), true));
}
$rs = sqlsrv_query($con,"select * from dbt");
while($row = sqlsrv_fetch_array($rs)){
    $data[] = $row;
}


-------------------------------------

问题排查:

Array ( [0] => Array ( [0] => 08001 [SQLSTATE] => 08001 [1] => 2 [code] => 2 [2] => [Microsoft][SQL Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. [message] => [Microsoft][SQL Server Native Client 10.0]Named Pipes Provider: Could not open a connection to SQL Server [2]. ) [1] => Array ( [0] => HYT00 [SQLSTATE] => HYT00 [1] => 0 [code] => 0 [2] => [Microsoft][SQL Server Native Client 10.0]Login timeout expired [message] => [Microsoft][SQL Server Native Client 10.0]Login timeout expired ) [2] => Array ( [0] => 08001 [SQLSTATE] => 08001 [1] => 2 [code] => 2 [2] => [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. [message] => [Microsoft][SQL Server Native Client 10.0]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. ) )

解决办法:

确认启用如下协议

QQ截图20140503193624.gif

设置端口

QQ截图20140503193203.gif


然后重启数据库