本文實(shí)例講述了PHP基于PDO調(diào)用sqlserver存儲(chǔ)過(guò)程的方法。分享給大家供大家參考,具體如下:
由于業(yè)務(wù)這邊存儲(chǔ)過(guò)程一直在sqlserver上面,所以要用php去調(diào)用它,然而我們本地的是windows,而線上又是linux,一開(kāi)始使用Yii框架的一些機(jī)制去調(diào)用發(fā)現(xiàn)在本地一直都是好的然而到線上就不行了,找了很多方案,最后找到了pdo這種方案,而本地使用的驅(qū)動(dòng)是sqlsrv線上是dblib所以需要注意下鏈接pdo時(shí)的驅(qū)動(dòng)形式,在取結(jié)果集的時(shí)候注意windows和linux好像有所不同,在我加上set nocount on后win若果直接取結(jié)果就可以拿到最后的,然而放到linux就沒(méi)了,氣死人的說(shuō),索性最后我把所有的都取一遍;
分享整理后的一個(gè)方法:
class StoredProcHelper { private static $type = [ 'integer'=>PDO::PARAM_INT, 'string'=>PDO::PARAM_STR, 'null'=>PDO::PARAM_NULL, 'boolean'=>PDO::PARAM_BOOL ]; private $sql = '';//此變量在下方說(shuō)明 private $params = [];//此變量在下方說(shuō)明 private $connect_info;//此變量在下方說(shuō)明 private $pdo_connect; public function __construct($connect_info,$sql,$params){ $this->sql = 'SET NOCOUNT ON;'.$sql; $this->params = $params; $this->connect_info = $connect_info; if(!empty($this->connect_info->dsn) && !empty($this->connect_info->username) && !empty($this->connect_info->password)){ $this->pdo_connect = new PDO($this->connect_info->dsn,$this->connect_info->username, $this->connect_info->password); } } public function ExecuteProc(){ $link = $this->pdo_connect->prepare($this->sql); foreach ($this->params as $key => $value){ $link->bindParam($key,$value,self::$type[strtolower(gettype($value))]); } $link->execute(); $i = 1; $res[0] = $link->fetchAll(); while($link->nextRowset()){ $res[$i] = $link->fetchAll(); $i++; } return $res; } }
使用舉例:
public static function Example($connect_info,$mobile){ $sql='declare @customParam int;exec you_proc @Mobile = :mobile,@OutParam=@customParam out;select @customParam as outName;'; $params = [ ':mobile'=>$mobile ]; $pdo = new StoredProcHelper($connect_info,$sql,$params); $res = $pdo->ExecuteProc(); var_dump($res); }
變量$sql和$params的形式如例子中表現(xiàn)的;
變量$connect_info的形式如下【因?yàn)楸救耸窃赮ii框架 下使用的,所以以此變量是直接根據(jù)Yii來(lái)獲取數(shù)據(jù)庫(kù)鏈接配置來(lái)進(jìn)行的,如果自己有所不同可以自行更改形式以及賦值形式,在框架中方便的是不同環(huán)境下直接獲取配置能分別獲取到是sqlsrv和dblib,不需要自行去更改】:
[ 'dsn' => 'sqlsrv:Server=xxxxxxxxxx;Database=xxxxx', 'username' => 'xxxxx', 'password' => 'xxxxxxxxxxxxxxxxxxxx', 'charset' => 'utf8', ] //或 [ 'dsn' => 'dblib:host=xxxxxxxxxx;dbname=xxxxx', 'username' => 'xxxxx', 'password' => 'xxxxxxxxxxxxxxxxxxxx', 'charset' => 'utf8', ],
更多關(guān)于PHP相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《PHP基于pdo操作數(shù)據(jù)庫(kù)技巧總結(jié)》、《php+Oracle數(shù)據(jù)庫(kù)程序設(shè)計(jì)技巧總結(jié)》、《PHP+MongoDB數(shù)據(jù)庫(kù)操作技巧大全》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門(mén)教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫(kù)操作入門(mén)教程》及《php常見(jiàn)數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家PHP程序設(shè)計(jì)有所幫助。