<?php
/**
* Created by PhpStorm.
* User: Huming
* Date: 2017-04-15
* Time: 22:41
* 用于连接SQL Server 2008R2数据库库,本机测试通过
*/
class MSSqlServerHelper
{
public $serverName = "localhost";
public $UID = "sa";
public $PWD = "A";
public $characterSet = "utf-8";
public $database = "yw";
public $conn;
/**
* 生成数据库连接
*/
public function __construct()
{
//必须指定编码,MS sqlserver出来是gbk编码的,不指定会出现乱码
//ReturnDatesAsStrings 指定返回时间为值,否则返回为object
$connectionInfo = array("Database" => $this->database, "UID" => $this->UID, "PWD" => $this->PWD, "CharacterSet" => $this->characterSet, 'ReturnDatesAsStrings' => true);
$this->conn = sqlsrv_connect($this->serverName, $connectionInfo);
if (!$this->conn) {
die('数据库连接失败' . sqlsrv_errors());
}
}
/**
* @执行查询,将查询到的记录以数组形式返回,并释放资源
*/
function execute_dql_array($sql)
{
$res = sqlsrv_query($this->conn, $sql);
if (!$res) {
die('操作失败' . sqlsrv_errors());
}
$arr = array();
//SQLSRV_FETCH_NUMERIC 为返回索引值的数组,SQLSRV_FETCH_ASSOC 为返回键值对的数组。
//不带参数则同时返回两种都有的数组
while ($row = sqlsrv_fetch_array($res, SQLSRV_FETCH_ASSOC)) {
$arr[] = $row;
}
sqlsrv_free_stmt($res);
return $arr;
}
/**
* 将查询到的数据以json形式返回
*/
function execute_dql_json($sql)
{
$arr = $this->execute_dql_array($sql);
//需要指定json返回为utf8编码
return json_encode($arr, JSON_UNESCAPED_UNICODE);
}
/**
* 返回记录数
*/
function execute_dql_rowsCount($sql)
{
$res = sqlsrv_query($this->conn, $sql);
if (!$res) {
die('操作失败' . sqlsrv_errors());
}
$rowsCount = 0;
//SQLSRV_FETCH_NUMERIC 为返回索引值的数组,SQLSRV_FETCH_ASSOC 为返回键值对的数组。
//不带参数则同时返回两种都有的数组
while ($row = sqlsrv_fetch_array($res, SQLSRV_FETCH_NUMERIC)) {
$rowsCount = $row[0];
}
sqlsrv_free_stmt($res);
return $rowsCount;
}
}