分为两个步骤php
php.ini
里面启用扩展,须要注意的问题是php版本以及是否为安全版本ODBC Driver
https://docs.microsoft.com/zh-cn/sql/connect/odbc/download-odbc-driver-for-sql-server?view=sql-server-2017,这个没啥注意的,你是啥系统就下载啥安装包就行linux 和 windows差很少,安装扩展的话直接能够用pecllinux
当你成功加载了能够在phpinfo()
里面看到,固然了,若是你安装扩展这些都有诸多问题都话,~你可真拉稀。
sql
我使用的tp版本是5.0和操做多个数据库,但愿能对你有所帮助thinkphp
// 帐号数据库 'UserDBConn' => [ 'type' => 'sqlsrv', // 服务器地址 'hostname' => '139.129.1.1', // 数据库名 'database' => 'DB3', // 用户名 'username' => 'xxxx', // 密码 'password' => 'tt123!@#', // 端口 'hostport' => '5188' ], // 金币数据库 'ScoreDBConn' => [ 'type' => 'sqlsrv', // 服务器地址 'hostname' => '139.129.1.1', // 数据库名 'database' => 'DB2', // 用户名 'username' => 'xxxx', // 密码 'password' => 'tt123!@#', // 端口 'hostport' => '5188' ], // 记录数据库 'RecordDBConn' => [ 'type' => 'sqlsrv', // 服务器地址 'hostname' => '139.129.1.1', // 数据库名 'database' => 'DB1', // 用户名 'username' => 'xxxx', // 密码 'password' => 'tt123!@#', // 端口 'hostport' => '5188' ],
在末尾追加数据库
/** * @param $DbconnName */ protected function Dbconn($DbconnName){ try{ $conn = Db::connect($DbconnName); }catch (\InvalidArgumentException $e){ echo '链接异常'; die; } return $conn; }
查询和增删改均可以调用query,若是你没有想要获取的结果集的话能够调用execute()
。windows
query()
有一个弊端,若是你的绑定参数的形式(非参数绑定)是直接写进sql的话,他有可能会判断你这个不是一个储存过程;
具体实现请查看thinkphp/library/think/db/Connection.php:368行,固然也不会有结果集返回。安全
你也能够用调用procedure()
,这个方法调用的话就必定会返回结果集。服务器
起初我就是这个问题,并无采用绑定参数的形式提交,直接写sql,就获取不到结果集,后来我在个人sql提行里面加入了SET NOCOUNT ON;
,才能勉强拿到返回,在文章最后我给出了我最开始获取的结果集的方案例子,可是真的拉稀,大家能够看看,不要吐槽。this
class Agent extends Model { public $Dbname = 'UserDBConn'; public function GetIndirectAgentList($agentId,$strAccount,$strSuperior,$iPageIndex,$pagesize) { $conn = $this->Dbconn($this->Dbname); try{ $TotalCount = 0; $res = $conn::query('exec [dbo].[Agent_GetAgentList] :agentId,:strAccount,:strSuperior,:iPageIndex,:pagesize,:TotalCount', [ 'agentId' => $agentId, 'strAccount' => [$strAccount, PDO::PARAM_STR], 'strSuperior' => [$strSuperior, PDO::PARAM_STR], 'iPageIndex' => [$iPageIndex, PDO::PARAM_INT], 'pagesize' => [$pagesize, PDO::PARAM_INT], 'TotalCount' => [$TotalCount, PDO::PARAM_INPUT_OUTPUT], ]); }catch (PDOException $e) { return false; } return $res; } }
很显然 这里并不会获取到@AgentID 以及 @TotalCount;他只会返回Agent_GetAgentList的结果集code
public function GetIndirectAgentList($agentId,$strAccount,$strSuperior,$iPageIndex,$pagesize) { $conn = $this->Dbconn($this->Dbname); try{ $res = $conn->query(' SET NOCOUNT ON; declare @AgentID int; declare @TotalCount int; exec [dbo].[Agent_GetAgentList] '.$agentId.',\''.$strAccount.'\',\''.$strSuperior.'\','.$iPageIndex.','.$pagesize.',@TotalCount output; select @AgentID as AgentID,@TotalCount as TotalCount '); }catch (PDOException $e) { return false; } return $res; }