PHP5.4连接sqlserver
1.下载微软的php连接驱动:SQLSRV30.EXE(5.4对应,后面的native client要用2012)/SQLSRV20.EXE(5.3对应,native client要用2008)/SQLSERV31.EXE对应5.5
2.解压SQLSERV30.EXE,拷贝对应extension到php的ext目录
3.配置php.ini
extension=php_sqlsrv_54_ts.dll(54为5.4版本,ts为线程安全,nts为非线程安全,带pdo的是用pdo方式连接,sqlsrvxx.exe里都有)
mssql.secure_connection = Off改为on 很多教程没写这个
4.重启IIS/Apache
5.在sqlserver服务器配置TCP/IP连接
6.在php服务器下载安装sqlserver native client(2014.11.13补充:win8下装上这玩意http://www.microsoft.com/en-us/download/details.aspx?id=20098)
7.测试代码
$database = "TimeTracker"; $uid = "sa"; $pwd = "123"; $Server = "192.168.0.152"; $conInfo=array('Database'=>$database,'UID'=>$uid,'PWD'=>$pwd); $link=sqlsrv_connect($Server,$conInfo); if( $link ){ // echo "Connection established.\n"; $query = 'SELECT * FROM T_Sys_UserInfo'; /* Set parameter values. */ $params = array(75123, 5, 741, 1, 818.70, 0.00); /* Prepare and execute the query. */ $stmt = sqlsrv_query( $link, $query, $params); while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC)) { echo $row['UseName'].", ".$row['RealName']."\n"; } } else{ //echo "Connection could not be established. "; print_r( sqlsrv_errors(), true); if( ($errors = sqlsrv_errors() ) != null) { foreach( $errors as $error ) { echo "SQLSTATE: ".$error[ 'SQLSTATE']."<br />"; echo "code: ".$error[ 'code']."<br />"; echo "message: ".$error[ 'message']."<br />"; } } die(""); }
PDO方式连接:
<?php header("Content-Type: text/html;charset=utf-8"); class mssql{ private $host; private $username; private $password; private $database; private $handle; private function __construct (Array $config){ $this -> host = $config['host']; $this -> username = $config['username']; $this -> password = $config['password']; $this -> database = $config['database']; $this -> init(); } private function init() { $dsn = 'sqlsrv:server = '.$this -> host.';database = '.$this->database; $this -> handle = new PDO($dsn,$this -> username, $this -> password); } public static function GetInstance(array $config = null) { if (null == $config) { return NULL; } static $db = null; if (null == $db) { $c = __CLASS__; $db = new $c($config); }; return $db -> handle; } } $config = array( 'host' => '192.168.0.152,1433', 'database' => 'TimeTracker', 'username' => 'sa', 'password' => '123' ); $mssql = mssql::GetInstance($config); $result = $mssql->query('SELECT * FROM T_Sys_UserInfo'); foreach($result as $row){ echo $row[2]; } ?>