一、安装SQL Driver for PHP 2.0
下载SQL Driver for PHP2.0,地址是:http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx
解压后根据PHP的版本选择对应的.dll文件,放入PHP扩展目录。PHP版本对应的.dll是(在压缩包内的SQLSRV_Readme.html里):
Driver file |
PHP version |
Thread safe? |
Use with PHP .dll |
---|---|---|---|
php_sqlsrv_53_nts_vc6.dll php_pdo_sqlsrv_53_nts_vc6.dll |
5.3 |
no |
php5.dll |
php_sqlsrv_53_nts_vc9.dll php_pdo_sqlsrv_53_nts_vc9.dll |
5.3 |
no |
php5.dll |
php_sqlsrv_53_ts_vc6.dll php_pdo_sqlsrv_53_ts_vc6.dll |
5.3 |
yes |
php5ts.dll |
php_sqlsrv_53_ts_vc9.dll php_pdo_sqlsrv_53_ts_vc9.dll |
5.3 |
yes |
php5ts.dll |
php_sqlsrv_52_nts_vc6.dll php_pdo_sqlsrv_52_nts_vc6.dll |
5.2 |
no |
php5.dll |
php_sqlsrv_52_ts_vc6.dll php_pdo_sqlsrv_52_ts_vc6.dll |
5.2 |
yes |
php5ts.dll |
接下来修改PHP.ini文件,添加以下几条命令(以PHP5.2,Thread Safe版本为例):
extension=php_pdo.dll extension=php_sqlsrv_52_ts_vc6.dll extension=php_pdo_sqlsrv_52_ts_vc6.dll 完成后重启Apache,通过phpinfo();查看安装结果。如果出现PDO_sqlsrv一栏,就说明驱动安装成功。 二、连接数据库 连接SQL Server 2008有两种方式,即Windows认证和Windows与SQL的混合认证。对于两种认证,使用的连接方式也有所不同。 使用Windows认证连接时,代码为: <?php |
|
使用混合认证模式时,代码为: <?php $serverName = "服务器IP地址"; $database = "数据库名";
// Get UID and PWD from application-specific files. $uid = file_get_contents("C:/AppData/uid.txt"); $pwd = file_get_contents("C:/AppData/pwd.txt");
try { $conn = new PDO( "sqlsrv:server=$serverName;Database = $database", $uid, $pwd); $conn->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION ); }
catch( PDOException $e ) { die( "Error connecting to SQL Server".$e->getMessage() ); }
echo "Connected to SQL Server/n";
$query = 'select * from 表名'; $stmt = $conn->query( $query ); while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ){ print_r( $row ); }
// Free statement and connection resources. $stmt = null; $conn = null; ?>
在使用混合认证时,微软建议尽量避免使用“sa”作为用户ID,而且用户名和密码不要直接出现在代码中,而是写入服务器上某一文件内,以保证数据库的安全。 更多信息可查看压缩包内提供的文档SQLSRV_Help.chm |