<?php /* * @Author: HUANGYUAN * @Date: 2017-03-01 16:32:22 * @Last Modified by: huangyuan413026@163.com * @Last Modified time: 2017-03-01 17:53:53 * @Description: 使用odbc鏈接到sqlserver,PHP必須開啓php_pdo_odbc擴展 */ namespace app\index\controller; use PDO;//導入PDO class login { public function index(){ //如下三個mssqldriver,使用任意一個均可以 $mssqldriver = '{SQL Server}'; $mssqldriver = '{SQL Server Native Client 11.0}'; $mssqldriver = '{ODBC Driver 11 for SQL Server}'; $hostname='123.123.123.123,1414'; $dbname='dbname'; $username='user'; $password='pwd'; //使用ODBC方式鏈接 $dbDB = new PDO("odbc:Driver=$mssqldriver;Server=$hostname;Database=$dbname", $username, $password); //沒有安裝sqlsrv驅動時沒法使用,error:could not find driver // $dbDB = new PDO("sqlsrv:Server=$hostname;Database=$dbname", $username, $password); $sql = "SELECT * FROM Users"; foreach ($dbDB->query($sql) as $row) { var_dump($row); } exit; } }
<?php return [ // 數據庫類型 'type' => 'Sqlsrv', //必須輸入
// 用戶名 'username' => 'username', // 密碼 'password' => 'pwd', // 鏈接dsn,驅動、服務器地址和端口、數據庫名稱 'dsn' => 'odbc:Driver={SQL Server};Server=123.123.123.123,1414;Database=dbname', ];
<?php /* * @Author:HUANGYUAN * @Date: 2017-03-01 16:32:22 * @Last Modified by: huangyuan413026@163.com * @Last Modified time: 2017-03-02 10:19:19 * @Description: 使用odbc鏈接到sqlserver,PHP必須開啓php_pdo_odbc擴展 */ namespace app\index\controller; use think\Db; //必須先導入db類,不然不能使用 class login { public function index(){ $user = Db::table('Users')->where('userid',1)->select(); print_r($user); } }
$dbDB = new PDO("sqlsrv:Server=$hostname;Database=$dbname", $username, $password);