728x90

PHP 절차지형 방식으로 MySQL 을 연동한 코드를 PDO 방식으로 변환할 때 필요한 정보를 적어둔다.

PDO 는 CUBRID, MS SQL Server, Firebird/Interbase, IBM, Informix, MySQL, Oracle, ODBC and DB2, PostgreSQL, SQLite, 4D 등 12가지 DB를 지원한다.

 

PHP 절차지향
PDO
 mysql_fetch_assoc($result)  $stmt->fetch(PDO::FETCH_ASSOC)
 mysql_num_rows($result)  $stmt->rowCount()
 while ($row = mysql_fetch_assoc($result)) {}  foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {}

 

SELECT 변환 예제

 $sql="select count(*), access from members where userID='".$userID."'";
 $result=mysqli_query($db,$sql);
 if($row=mysqli_fetch_row($result)){
 $sql="select count(*), access from members where userID=?";
 $params = array($userID);
 $stmt = $this->db->prepare($sql);
 $stmt->execute($params);
 if($row = $stmt->fetch()){

 

Update 변환 예제

 $sql = "UPDATE rb_accessLog SET hit=hit+1 Where ipaddr='".$access_ip."' and LogID='".$userID."'";
 $result=mysqli_query($db,$sql);
 $sql = "UPDATE rb_accessLog SET hit=hit+1 Where ipaddr=? and LogID=?";
 try {
    $this->db->beginTransaction();
    $params = array($access_ip,$userID);
    $stmt = $this->db->prepare($sql);
    $stmt->execute($params);
    $this->db->commit();
 } catch (PDOException $pex) {
    $this->db->rollBack();
    echo "에러 : " . $pex -> getMessage();
 }

 

Insert 변환 예제

 $sql ="INSERT INTO bbs_imgpath (uid,relateduid,imgpath) values(NULL,";
 $sql.="'".$uid."', '".$v."')";
 mysqli_query($this->db,$sql);
 $key = "uid,relateduid,imgpath";
 $val = "NULL,$uid,$v";
 $this->getDbInsert('bbs_imgpath', $key, $val);

 

getDbInsert 함수는 아래와 같이 만들었다.

<?php
 function getDbInsert($table$key$val) {
        try {
            $params = explode(','$val); // 문자열을 분리하여 배열로 만듬
            $this->db->beginTransaction();
            $sql = "insert into " . $table . " (" . $key . ") values(" . $this->recur_quot(count($params)) . ")";
            $stmt = $this->db->prepare($sql);
            $status = $stmt->execute($params); // $params 는 배열 값
            if ($status) {
                $this->db->commit();
                return 1;
            } else {
                return 0;
            }
        } catch (PDOException $pex) {
            $this->db->rollBack();
            echo "에러 : " . $pex->getMessage();
        }
    }
 
    public function recur_quot($cnt) {
        $R = array();
        for ($i = 0$i < $cnt$i++) {
            array_push($R"?");
        }
        return implode(","$R); // 배열을 문자열로
    } 
 
?
 

 

Delete 변환 예제

 $sql = "DELETE FROM bbs_imgpath where imgpath='".$v."' and relateduid=".$uid;
 mysqli_query($this->db,$sql);
 
 $where = "imgpath=? and relateduid=?";
 $params = array($v,$uid);
 $this->getDbDelete('bbs_imgpath', $where, $params);

 

getDbDelete 함수는 아래와 같이 만들었다.

 
 
<?php
    public function getDbDelete($table$where$params) {
        if ($this->isDataExisted($table$where$params)) {
            try {
                $this->db->beginTransaction();
                $sql = "delete from " . $table . ($where ? ' where ' . $where : '');
                $stmt = $this->db->prepare($sql);
                $status = $stmt->execute($params);
                if ($status) {// action 실행여부에 대한 결과이지 실제 데이터 삭제와는 무관하네.
                    $this->db->commit();
                    return 1// 삭제 성공
                } else {
                    return 0// 삭제 실패
                }
            } catch (PDOException $pex) {
                $this->db->rollBack();
                echo "에러 : " . $pex->getMessage();
            }
        } else {
            return 0// 삭제할 데이터가 없음
        }
 
    }
 
    // 삭제할 데이터의 존재 유무 파악
    public function isDataExisted($table$where$params) {
        $sql = 'select * from ' . $table . ($where ? ' where ' . $where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        if ($row = $stmt->fetch()) {
            return $row;
        } else {
            return false;
        }
    }
 
?>
 

 

사용자 함수

편리하게 사용하기 위해 만든 함수는 아래와 같이 변경하면 된다.

다만, 검색조건을 입력시 SQL Injection 필터링 함수를 한번 거쳐서 where 조건문에서 해킹 방지를 해주는 것은 필수요소다.

    function getDbData($table,$where,$column) {
        global $db;
        $sql ='select '.$column.' from '.$table.($where?' where '. $where:'');
        //echo $sql;
        $result = mysqli_query($db,$sql);
        $row = mysqli_fetch_array($result);
        return $row;
    }
     // 검색조건에 일치하는 데이터 가져오기
    public function getDbData($table, $where, $column, $returntype = '') {
        $sql = 'select ' . $column . ' from ' . $table . ($where ? ' where ' . $where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        if ($returntype == 1) {
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            return $stmt->fetch();
        }
    }
     // 검색조건에 일치하는 데이터 가져오기
    public function getDbDataAll($table, $where, $column) {
        $sql = 'select ' . $column . ' from ' . $table . ($where ? ' where ' . $this->getSqlFilter($where) : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll();
    }

 

 

관련으로 만든 Class 대부분은 아래와 같다.

 
<?php
class DBDataClass {
    protected $db// 변수를 선언한 클래스와 상속받은 클래스에서 참조할 수 있다.
 
    public function __construct() {
        $this->dbConnect();
        // construct 메소드는 객체가 생성(인스턴스화)될 때 자동으로 실행되는 특수한 메소드다.
    }
 
    private function dbConnect() {
        require_once 'dbinfo.php';
        try {
            // SQL PDO 객체 생성
            $this->db = new PDO(_DSN, _DBUSER, _DBPASS);
            $this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, FALSE);
        } catch(PDOException $ex) {
            die("오류 : " . $ex->getMessage());
        }
    }
 
    // 신규 자료 추가(ok)
    function getDbInsert($table$key$val) {
        try {
            $params = explode(','$val); // 문자열을 분리하여 배열로 만듬
            $this->db->beginTransaction();
            $sql = "insert into " . $table . " (" . $key . ") values(" . $this->recur_quot(count($params)) . ")";
            $stmt = $this->db->prepare($sql);
            $status = $stmt->execute($params); // $params 는 배열 값
            $this->db->commit();
            return 1;
        } catch (PDOException $pex) {
            $this->db->rollBack();
            echo "에러 : " . $pex->getMessage();
            return 0;
        }
    }
 
    public function recur_quot($cnt) {
        $R = array();
        for ($i = 0$i < $cnt$i++) {
            array_push($R"?");
        }
        return implode(","$R); // 배열을 문자열로
    }
 
    function getDbUpdate($table$set$params$where) {
        $sql = "update " . $table . " set " . $set . ($where ? ' where ' . $where : '');
        try {
            $this->db->beginTransaction();
            $stmt = $this->db->prepare($sql);
            $status = $stmt->execute($params);
            $this->db->commit();
            return 1;
        } catch (PDOException $pex) {
            $this->db->rollBack();
            echo "에러 : " . $pex->getMessage();
            return 0;
        }
    }
 
    public function getDbDelete($table$where$params) {
        if ($this->isDataExisted($table$where$params)) {
            try {
                $this->db->beginTransaction();
                $sql = "delete from " . $table . ($where ? ' where ' . $where : '');
                $stmt = $this->db->prepare($sql);
                $status = $stmt->execute($params);
 
                $this->db->commit();
 
                return 1// 삭제 성공
            } catch (PDOException $pex) {
                $this->db->rollBack();
                echo "에러 : " . $pex->getMessage();
            }
        } else {
            return 0// 삭제할 데이터가 없음
        }
 
    }
 
    // 삭제할 데이터의 존재 유무 파악
    public function isDataExisted($table$where$params) {
        $sql = 'select * from ' . $table . ($where ? ' where ' . $where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        if ($row = $stmt->fetch()) {
            return $row;
        } else {
            return false;
        }
    }
 
 
    // 검색조건에 일치하는 데이터 가져오기
    public function getDbData($table$where$column$returntype = '') {
        $sql = 'select ' . $column . ' from ' . $table . ($where ? ' where ' . $where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        if ($returntype == 1) {
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } else {
            return $stmt->fetch();
        }
    }
 
    // 검색조건에 일치하는 데이터 가져오기
    public function getDbDataAll($table$where$column) {
        $sql = 'select ' . $column . ' from ' . $table . ($where ? ' where ' . $where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll();
    }
 
    // DB Query result 함수
    function getDbresult($table,$where,$column) {
        $sql = 'select ' . $column . ' from ' . $table . ($where ? ' where ' .$where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll();
    }
 
    // DB 레코드 총 수(ok)
    public function getDbRows($table$where) {
        $sql = 'select count(*) from ' . $table . ($where ? ' where ' . $where : '');
        $stmt = $this->db->prepare($sql);
        $stmt->execute();
        if ($row = $stmt->fetch()) {
            return $row[0];
        } else {
            return false;
        }
    }
}
?> 

 

 

 

 

블로그 이미지

Link2Me

,