狮子座男

导航

PHP连接SQLServer2012两例

首先放上

PHP连接SQLServer的驱动下载地址

http://php.net/manual/zh/ref.pdo-sqlsrv.php

另外PHP for IIS管理工具 大家可以自己搜索一下 很久以前下的。现在忘记地址了。

PHPManagerForIIS-1.1.2-x64.msi

 

第一个是比较基础的,直接创建conn 连接本机的SQLExpress实例

    $conn = new PDO("sqlsrv:server=.\SQLExpress;Database=thinkphp","admin","pass1234");
    //$conn = new PDO("sqlsrv:Server=127.0.0.1/Express; Database=MyeCharts", "admin", "pass1234"); 
    $query = 'select top 1 * from think_data';  
    $stmt = $conn->query( $query );  
    while ( $row = $stmt->fetch( PDO::FETCH_ASSOC ) ) {  
       //print_r( $row );  
    }  

第二个是网上搜罗到的创建了类来控制 连接远程服务器。

class mssql{
        private $host;
        private $username;
        private $password;
        private $database;
        private $handle;
        private function __construct (Array $config){
            $this -> host = $config['DB_HOST'];
            $this -> username = $config['DB_USER'];
            $this -> password = $config['DB_PWD'];
            $this -> database = $config['DB_NAME'];
            $this -> init();
        }
        private function init() {
            $dsn = 'sqlsrv:server = '.$this -> host.';database = '.$this->database;
            $this -> handle = new PDO($dsn,$this -> username, $this -> password);
        }
        public static function GetInstance(array $config = null) {
            if (null == $config) {
                return NULL;
            } 
            static $db = null;
            if (null == $db) {
                $c = __CLASS__;
                $db = new $c($config);
            };
            return $db -> handle;
        }
    }

调用方法

    $config = array(
        'DB_HOST' => 'servername,1800',
        'DB_NAME' => formname,
        'DB_USER' => 'admin',
        'DB_PWD' => 'pass1234'
    );
    $mssql = mssql::GetInstance($config);
    $result = $mssql->query('SELECT MAX(formID) FROM fromname);
    foreach($result as  $row){
        $id = $row[0];
        echo $id;
    }

posted on 2014-07-24 17:18  狮子座男  阅读(1603)  评论(0编辑  收藏  举报