这篇文章主要介绍了php基于pdo调用sqlserver存储过程通用方法,结合实例形式分析了基于yii框架采用pdo调用sqlserver存储过程的相关操作步骤与实现技巧,需要的朋友可以参考下
本文实例讲述了php基于pdo调用sqlserver存储过程的方法。分享给大家供大家参考,具体如下:
由于业务这边存储过程一直在sqlserver上面,所以要用php去调用它,然而我们本地的是windows,而线上又是linux,一开始使用yii框架的一些机制去调用发现在本地一直都是好的然而到线上就不行了,找了很多方案,最后找到了pdo这种方案,而本地使用的驱动是sqlsrv线上是dblib所以需要注意下链接pdo时的驱动形式,在取结果集的时候注意windows和linux好像有所不同,在我加上set nocount on后win若果直接取结果就可以拿到最后的,然而放到linux就没了,气死人的说,索性最后我把所有的都取一遍;
分享整理后的一个方法:
class storedprochelper
{
private static $type = [
'integer'=>pdo::param_int,
'string'=>pdo::param_str,
'null'=>pdo::param_null,
'boolean'=>pdo::param_bool
];
private $sql = '';//此变量在下方说明
private $params = [];//此变量在下方说明
private $connect_info;//此变量在下方说明
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的形式如例子中表现的;
变量$connect_info的形式如下【因为本人是在yii框架 下使用的,所以以此变量是直接根据yii来获取数据库链接配置来进行的,如果自己有所不同可以自行更改形式以及赋值形式,在框架中方便的是不同环境下直接获取配置能分别获取到是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',
],
以上就是php基于yii框架使用pdo调用sqlserver存储过程的方法介绍的详细内容。