php基於Yii架構使用PDO調用sqlserver預存程序的方法介紹

來源:互聯網
上載者:User
這篇文章主要介紹了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',],

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.