Skip to content

CHICPRO

  • Life Log
  • Cycling Log
  • Photo Log
    • Portrait
    • Landscape
    • Flower
    • Etc
  • Coding Log
  • Information

[PHP] Database class for MySQL which uses the PDO extension

2018-04-12 by 편리

PHP Data Object(PDO)를 이용하여 MySQL DB를 사용하기 위한 Class 이다. Prepared statements 와 named placeholder 를 사용하도록 코드를 작성했다. Class 사용 전 DB_NAME, DB_USER 등의 정보를 설정해야 한다. 아래 코드는 PHP 7.0.0 버전 이상에서 사용할 수 있다.

<?php

// DB 설정
define('DB_HOST', 'localhost');
define('DB_NAME', '');
define('DB_USER', '');
define('DB_PASS', '');

define('DB_ERROR_MODE', ''); // SILENT, WARNING

class DB
{
    public $pdo;
    public $error;

    protected $host;
    protected $user;
    protected $pass;
    protected $dbname;
    protected $stmt;
    protected $options;

    public function __construct(array $options = array())
    {
        require_once NT_CONFIG_PATH.DIRECTORY_SEPARATOR.'db.php';

        $this->options = array();

        switch (DB_ERROR_MODE) {
            case 'SILENT':
                $this->options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_SILENT;
                break;
            case 'WARNING':
                $this->options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_WARNING;
                break;
            default:
                $this->options[\PDO::ATTR_ERRMODE] = \PDO::ERRMODE_EXCEPTION;
                break;
        }

        if (!empty($options))
            $this->options = array_merge($this->options, $options);

        $this->host   = DB_HOST;
        $this->user   = DB_USER;
        $this->pass   = DB_PASS;
        $this->dbname = DB_NAME;

        try {
            $this->pdo = new \PDO('mysql:host='.$this->host.';dbname='.$this->dbname.';charset=utf8', $this->user, $this->pass, $this->options);
        } catch(\Exception $e) {
            $this->error = 'Connection failed: ' . $e->getMessage();
        }
    }

    public function prepare(string $query)
    {
        $this->stmt = $this->pdo->prepare($query);
    }

    public function bindValue($placeholder, $value, $type = null)
    {
        if (is_null($type)) {
            switch (true) {
                case is_int($value):
                    $type = \PDO::PARAM_INT;
                    break;
                case is_bool($value):
                    $type = \PDO::PARAM_BOOL;
                    break;
                case is_null($value):
                    $type = \PDO::PARAM_NULL;
                    break;
                default:
                    $type = \PDO::PARAM_STR;
                    break;
            }
        }

        $this->stmt->bindValue($placeholder, $value, $type);
    }

    public function bindValueArray(array $params)
    {
        if (!empty($params)) {
            foreach ($params as $key => $val) {
                $this->bindValue($key, $val);
            }
        }
    }

    public function execute(array $param = array())
    {
        if (is_array($param) && !empty($param)) {
            foreach($param as $key => $val) {
                $this->bindValue($key, $val);
            }
        }

        return $this->stmt->execute();
    }

    public function fetchAll($args = \PDO::FETCH_ASSOC)
    {
        return $this->stmt->fetchAll($args);
    }

    public function fetch($args = \PDO::FETCH_ASSOC)
    {
        return $this->stmt->fetch($args);
    }

    public function rowCount()
    {
        return $this->stmt->rowCount();
    }

    public function lastInsertId(){
        return $this->pdo->lastInsertId();
    }

    public function beginTransaction(){
        return $this->pdo->beginTransaction();
    }

    public function commit(){
        return $this->pdo->commit();
    }

    public function rollBack(){
        return $this->pdo->rollBack();
    }

    public function debugDumpParams(){
        return $this->stmt->debugDumpParams();
    }

    public function errorInfo()
    {
        $error = $this->stmt->errorInfo();
        $this->error = $error[0] . ' ' . $error[2];
    }

    public function close()
    {
        $this->pdo = null;
    }

    public function __call($method, $args)
    {
        if (method_exists($this->pdo, $method)) {
            return call_user_func_array(array(&$this->pdo, $method), $args);
        } else if (method_exists($this->stmt, $method)) {
            return call_user_func_array(array(&$this->stmt, $method), $args);
        } else {
            return 'Method \'' . $method . '\' not exists';
        }
    }
}

Post navigation

Previous Post:

Harman Kardon Esquire Mini Brown Esquire Mini Speaker

Next Post:

Dropzonejs를 이용한 Drag & Drop 파일 업로드 구현

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Recent Posts

  • php 배열 연산에서 + 와 array_merge 의 차이
  • pcntl_fork 를 이용한 다중 프로세스 실행
  • 아이폰 단축어를 이용하여 주중 공휴일엔 알람 울리지 않게 하기
  • 구글 캘린더 전체일정 재동기화
  • OpenLiteSpeed 웹서버에 HTTP 인증 적용
  • OpenLiteSpeed 웹어드민 도메인 연결
  • WireGuard를 이용한 VPN 환경 구축
  • Ubuntu 22.04 서버에 OpenLiteSpeed 웹서버 세팅
  • 맥 vim 세팅
  • 우분투 시스템 터미널쉘 zsh 로 변경

Recent Comments

  • 편리 on 업무관리용 그누보드 게시판 스킨
  • 임종섭 on 업무관리용 그누보드 게시판 스킨
  • 캐논 5D 펌웨어 | Dslr 펌웨어 업그레이드 방법 82 개의 베스트 답변 on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • Top 5 캐논 5D 펌웨어 Top 89 Best Answers on 캐논 EOS 30D 펌웨어 Ver 1.0.6 , EOS 5D 펌웨어 Ver 1.1.1
  • 편리 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 임팀장 on 워드프레스 애니메이션 gif 파일을 mp4로 변환하여 출력하기
  • 편리 on Notepad++ NppFTP 플러그인 수동 설치
  • paul-j on Notepad++ NppFTP 플러그인 수동 설치
  • YS on Windows 10 iCloud 사진 저장 폴더 변경
  • 편리 on Docker를 이용한 Centos7 + httpd + php 5.4 개발환경 구축

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
© 2025 CHICPRO | Built using WordPress and SuperbThemes