티스토리 뷰

반응형

mssql에 연결해서 사용하기 위해서 간단하게 작성하였습니다.. 혹시 mysql과 연결 하고 싶다면 약간만 수정하면 되었습니다..
그리고 경우에 따라서 필요한 함수를 추가하면 됩니다.

<?php
class Connection
{
private $is_new = false; // 새로운 디비 링크
private $host = 'localhost'; // 호스트
private $user = 'sa'; // 계정
private $pass = 'password'; // 암호
private $source = 'DatabaseName'; // 데이터베이스

// 에러처리
var $error = false;
var $message = "";

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;
}
}
?>

간단 사용예
$conn = new Connection();
$sql = "커리문";
if ( $conn->query( $sql ) )
{
while ( $row = $conn->fetch() )
{
if ( $row )
{
// 레코드 처리
}
}
}
$conn->close();
$conn = null;

실제로 한때 웹사이트 운영할때 사용했습니다.
환경은 iis에서 php를 셋팅하고 mssql로 연결했습니다.


728x90
반응형
댓글