MSSQL PHP Connection

태어나 생전 처음으로 접해본 윈도우서버와 MSSQL DB
Windows 2012 서버 MSSQL 에서 PHP를 적용하여 DB 다루기
아래 내용은 SMS 웹연동시 적용했던 내용입니다.

​

서버 환경

1. Windows Server 2012 R2 (버전 6.2 / 빌드 9200)
2. IIS 버전 : IIS 8
3. MSSQL : Microsoft SQL Server 2008 R2 (RTM)
4. PHP : PHP 7.4

MSSQL PHP Connection

class Connection {
    
    private $is_new = false; // 새로운 디비 링크
    private $host = 'DB IP';  // 호스트
    private $user = 'dbUser'; // 계정
    private $pass = 'dbUserPass'; // 암호
    private $source = 'dbName'; // 데이터베이스

    // 에러처리
    var $error = false;
    var $message = "";
    var $conn;
    var $stmt;
    
    function Connection() {
        $this->conn = $this->mssql();
    }
    
    function mssql($is_new = false) {
        if(!$this->conn || $is_new) {
            $connectionInfo = array( "UID"=> $this->user, "PWD"=> $this->pass, "Database"=>$this->source );
            $this->conn = sqlsrv_connect( $this->host, $connectionInfo );
    
            if ( $this->conn ) {
                //print( "데이터베이스에 연결 성공했습니다.<br>" );
            }
            else {            
                die( print( "데이터베이스에 연결 실패했습니다.<br>" ) );
            }
        }
        return $this->conn;
    }
    
    function close() {
        if ( $this->stmt ) {
            if ( !sqlsrv_free_stmt( $this->stmt ) ) $this->error();
        }
        if($this->conn) {
            if ( !sqlsrv_close( $this->conn ) ) $this->error();
        }
    }
    
    function error() {
        $this->error = true;
        $this->message = sqlsrv_errors() . "\n<br />" . $this->query . "\n<br />";
    }
    
    function prepare( $query, $params = null ) {
        $this->query = $query;
        $this->params = $params;
        $this->stmt = sqlsrv_query( $this->conn, $this->query, $this->params );
        $this->execute();
    
        if( $this->stmt === false ) {
            $this->error();
        }
    
        return $this->stmt;
    }
    
    private function execute() {
        sqlsrv_execute( $this->stmt );
    }
    
    function query( $query, $params = null ) {
        $this->query = $query;
        $this->params = $params;
        $this->stmt = sqlsrv_query($this->conn, $this->query, $this->params); 
    
        if( $this->stmt === false ) {
            $this->error();
        }
    
        return $this->stmt;
    }
    
    function nextResult() {
        $next_result = sqlsrv_next_result( $this->stmt);
        return $next_result;
    }
    
    function fetch( $mode = 'array') {
        if ( isset( $this->stmt ) ) {
            switch( $mode ) {
                case 'array':
                return sqlsrv_fetch_array( $this->stmt );
                break;
            case 'object':
                return sqlsrv_fetch_object( $this->stmt );
                break;
            }
        }
        return null;
    }
}

SELECT 예제 1 ( 여러 데이터 가져오기 )

– AJAX 페이지 처리하기 위해 아래와 같이 데이터를 가공하여 가져옴.
– MSSQL은 페이지 처리가 MYSQL과 다르게 처음 접해본 나에겐 힘든 부분이 있었습니다.

/**
 * SMs Content 목록 가져오기
 * $PAGE_NO 페이지 번호
 * $PAGE_SIZE 한페이지에 보여줄 ROW
 */
function get_smsContent_list($PAGE_NO, $PAGE_SIZE) {
    
    global $office;

    $sql_search = "";
    $sql_search2 = "";
    
    if($office['BranchID'] != '0000') {
        $sql_search .= " AND BranchID = '{$office['BranchID']}' ";
        $sql_search2 .= " WHERE BranchID = '{$office['BranchID']}' ";
    }
    
    $conn = new Connection();
    $sql = "SELECT 
                rownum,
                BranchID,
                SMSCode,
                Title,
                Content,
                UptDT,
                totalCnt
            FROM
                (
                    SELECT 
                        ROW_NUMBER() OVER(ORDER BY SMSCode DESC) AS rownum,
                        BranchID,
                        SMSCode,
                        Title,
                        Content,
                        UptDT,
                        COUNT(*) OVER() AS totalCnt 
                    FROM 
                        tblSMSContent
                    {$sql_search2}
                ) A
            WHERE                
                rownum BETWEEN ( ( {$PAGE_NO} - 1 ) * {$PAGE_SIZE} ) + 1 
                AND ( {$PAGE_NO} * {$PAGE_SIZE} )
                {$sql_search}
            ORDER BY
                SMSCode DESC";
    $conn->query($sql);
    $response = new stdClass();
    while($row = $conn->fetch()) {
        $response->rows[] = array(
            "BranchID" => $row['BranchID'],
            "SMSCode" => $row['SMSCode'],
            "Title" => iconv('euc-kr', 'utf-8', $row['Title']),
            "Content" => iconv('euc-kr', 'utf-8', $row['Content']),
            "SendCnt" => $row['SendCnt'],
            "CrtDT" => $row['CrtDT'],
            "UptDT" => $row['UptDT'],
            "CrtID" => $row['CrtID'],
            "UptID" => $row['UptID'],
            "totalCnt" => $row['totalCnt']
        );
        $totalCount = $row['totalCnt'];
    }

    $total_count = $totalCount;  // 검색된 자료 총 갯수

    //한페이지에 보여질 리스트 숫자..
    $rows = ($PAGE_SIZE) ? $PAGE_SIZE : 25;
    $total_page  = ceil($total_count / $rows);  // 전체 페이지 계산
    if (!$PAGE_NO) $PAGE_NO = 1; // 페이지가 없으면 첫 페이지 (1 페이지)
    //$from_record = ($page - 1) * $rows; // 시작 열을 구함
    
    $response->page = $PAGE_NO; // 현재페이지
    $response->total = $total_page; // 총페이지
    $response->records = $total_count; // 총 자료수
    $response->para = array_filter($_POST);

    $conn->close();
    $conn=null;

    return $response;
}

SELECT 예제2) 단일 데이터 가져오기

/**
 * SMs Content 단일 목록 가져오기
 * $BranchID 가맹점 고유번호
 * $SMSCode 가맹점별 SMS 고유번호
 */
function get_smsContent_Unit($BranchID, $SMSCode) {

    global $office;

    if(!$SMSCode) {
        die();
    }

    $BranchID = ($office['BranchID'] == '0000') ? $BranchID : $office['BranchID'];

    $conn = new Connection();
    $sql = "SELECT 
                *
            FROM
                tblSMSContent
            WHERE
                BranchID = '{$BranchID}' AND SMSCode = '{$SMSCode}' ";
    $conn->query($sql);
    $row = $conn->fetch();
    $response = array(
        "BranchID" => ($row['BranchID']) ? $row['BranchID'] : "",
        "SMSCode" => ($row['SMSCode']) ? $row['SMSCode'] : "",
        "Title" => iconv('euc-kr', 'utf-8', $row['Title']),
        "Content" => iconv('euc-kr', 'utf-8', $row['Content']),
    );
    $conn->close();
    $conn=null;

    return $response;
}

INSERT 예제)

– 문자 내용을 신규 등록시

$conn = new Connection();

// BranchID 별로 가장 높은 SMSCode 구하기 (테이블에 자동증가 필드가 없어서... )
$sql = "SELECT 
            max(SMSCode) as SMSCode
        FROM
            tblSMSContent
        WHERE
            BranchID = '{$office['BranchID']}' ";
$conn->query($sql);
$rs = $conn->fetch();
$SMSCode = $rs['SMSCode'] + 1;

// SMS 내용 신규 등록
$sql = "INSERT INTO 
            tblSMSContent
            ( BranchID, SMSCode, Title, Content, SendCnt, CrtDt, UptDt, CrtID, UptID )
        VALUES 
            ( '{$BranchID}', '{$SMSCode}', '{$Title}', '{$Content}', '{$SendCnt}', '{$CrtDt}', '{$UptDt}', '{$CrtID}', '{$UptID}' )";
$conn->query($sql);
$conn->close();
$conn = null;

UPDATE 예제)

– 문자 내용을 수정 저장시

$conn = new Connection();
    
// SMS 내용 신규 등록
$sql = "UPDATE 
            tblSMSContent
        SET
            Title = '{$Title}',
            Content ='{$Content}',
            UptDt = '{$UptDt}'
        WHERE
            BranchID = '{$office['BranchID']}' AND SMSCode = '{$SMSCode}' ";
$conn->query($sql);
$conn->close();
$conn = null;