PHP调用SQL Server存储过程背景
本示例演示了利用PHP的PDO扩展调用SQL Server存储过程的具体实现方式,供开发者参考使用。
鉴于业务逻辑依赖SQL Server上的存储过程,需通过PHP进行调用。开发环境为Windows,生产环境为Linux。初期尝试使用Yii框架内置机制,发现本地运行正常但部署至线上后失效。经排查,最终确定采用PDO方案。需注意,本地通常使用sqlsrv驱动,而线上多为dblib驱动,连接时的驱动形式需区分对待。此外,Windows与Linux环境下结果集的读取行为存在差异:在本地执行时,若直接获取结果集,加上`set nocount on`后可获得最终结果;但在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程序开发人员有所帮助。