[PHP] MySQL 사용 기초 클래스(BasicMySQL)

2026. 5. 25. 23:36·Programming/Web

BasicMySQL

PHP에서 MySQL 을 사용하기 위한 기초 클래스

<?php

/**
* @author : Sergio Soares 2016 (PHP 7 &^ only!)
* BasicMySQL Database Connection Class
* @access public
*/
class BasicMySQL {
    /**
    * MySQL server hostname
    * @access protected
    * @var string
    */
    protected $host;

    /**
    * MySQL username
    * @access protected
    * @var string
    */
    protected $user;

    /**
    * MySQL user's password
    * @access protected
    * @var string
    */
    protected $pass;

    /**
    * MySQL Name of database to use
    * @access protected
    * @var string
    */
    protected $name;

    /**
    * MySQL Resource link identifier stored here
    * @access private
    * @var string
    */
    private $con;

    /**
    * MySQL Stores error messages for connection errors
    * @access private
    * @var string
    */
    private $connectError;

    /**
    * BasicMySQL constructor
    * @param string host (MySQL server hostname)
    * @param string User (MySQL User Name)
    * @param string Pass (MySQL User Password)
    * @param string Name (Database to select)
    * @access public
    */
    public function __construct($host,$user,$pass,$name)
    {
        $this->host=$host;
        $this->user=$user;
        $this->pass=$pass;
        $this->name=$name;
        $this->DBconnect();
    }

    /**
    * Establishes connection to MySQL server and selects a database
    * @return void
    * @access private
    */
    private function DBconnect()
    {
        // Make connection to MySQL server
    	try
    	{
    		$this->con = mysqli_connect($this->host,
              $this->user, $this->pass, $this->name);
    	}
    	catch (Error $e)
    	{
    		trigger_error ('Could not connect to server: '.$e->getMessage());
    		$this->connectError=true;
    	}
            
    }
    
    /**
    * Checks for errors
    * @return boolean
    * @access public
    */
    public function isError() : bool
    {
        if ( $this->connectError )
            return true;
        $error=mysqli_error ($this->con);
        if ( empty ($error) )
            return false;
        else
            return true;
    }

    /**
    * Returns an instance of a result class to fetch rows with
    * @param $sql string the database query to run
    * @return result
    * @access public
    */
    public function query($sql)
    {
    	
    	try
    	{
    		$queryRess=mysqli_query($this->con,$sql);
    	}
    	catch (Error $e)
    	{
    		trigger_error ('Query failed: '.$e->getMessage().' SQL: '.$sql);
    	}
        	
    	if (!$this->isError()) {
    		
        	return new class ($this,$queryRess) {
        		
        		/**
        		 * Instance of a result class providing database connection
        		 * @access private
        		 * @var BasicMySQL
        		 */
        		private $bsqli;
        		
        		/**
        		 * Query resource
        		 * @access private
        		 * @var resource
        		 */
        		private $query;
        		
        		/**
        		 * mySQL result constructor
        		 * @param object mysql   (instance of BasicMySQL class)
        		 * @param resource query (BasicMySQL query resource)
        		 * @access public
        		 */
        		public function __construct(& $bsqli,$query)
        		{
        			$this->bsqli=& $bsqli;
        			$this->query= $query;
        		}
        		
        		/**
        		 * Fetches a row from the result
        		 * @return array
        		 * @access public
        		 */
        		public function fetch() : array
        		{
        			$row=mysqli_fetch_array($this->query, MYSQLI_ASSOC);
        			return (array)$row;
        		}
        		
        		/**
        		 * Returns the number of rows selected
        		 * @return int
        		 * @access public
        		 */
        		public function size() : int
        		{
        			$size = mysqli_num_rows($this->query);
        			return $size;
        		}
        		
        		/**
        		 * Checks for BasicMySQL errors
        		 * @return boolean
        		 * @access public
        		 */
        		public function isError() : bool
        		{
        			return $this->bsqli->isError();
        		}
        		
        	};
        
    	}
        // Free result set
        mysqli_free_result($queryRess);
        mysqli_close($this->con);
    }
}

?>

 

사용법

<?php
$host = 'localhost';
$user = 'DB_ID';
$pass = 'DB_PW';
$name = 'DB_NAME';

$DB = new BasicMySQL($host,$user,$pass,$name);

	// SELECT

	if ($result = $DB->query("SELECT * FROM test ")){
						
        if (!defined('TABLE')) define ('TABLE',['col1','col2']);
            $jsonarray = array();
            while ($sqlReg=$result->fetch()) {
                $row_array['col1'] = $sqlReg[TABLE[0]];
				$row_array['col2'] = $sqlReg[TABLE[1]];              
            }
        }
    }

	// INSERT, UPDATE
    
    $query = "INSERT INTO test(col1, col2)";
    $query .= " values('".$col1."','".$col2."')";

    if ($result = $DB->query($query)){
        echo("OK");
    }
    else
    {
        echo("FAIL");
    }
?>

 

PHP7 에서 테스트 되었습니다.

'Programming > Web' 카테고리의 다른 글

[JSP] html table 내용을 엑셀로 Export  (0) 2025.12.23
HTML5 로컬 스토리지  (0) 2025.12.11
[Jquery] JSON file 읽어서 처리 하는 Javascript  (1) 2025.11.28
[PHP] 사진 파일 업로드  (0) 2025.11.19
'Programming/Web' 카테고리의 다른 글
  • [JSP] html table 내용을 엑셀로 Export
  • HTML5 로컬 스토리지
  • [Jquery] JSON file 읽어서 처리 하는 Javascript
  • [PHP] 사진 파일 업로드
레이조(RayCho)
레이조(RayCho)
개발자 레이조(RayCho)의 블로그입니다. 똑똑하게 배우고 기록하는 공간
  • 레이조(RayCho)
    레이(Ray)의 개발이야기
    레이조(RayCho)
  • 전체
    오늘
    어제
    • 분류 전체보기 (54) N
      • Programming (54) N
        • Python (5)
        • Flutter (4)
        • Delphi (20) N
        • Lazarus (1)
        • C#.NET (6) N
        • ASP.NET (5)
        • Database (5)
        • Game Dev (0)
        • Web (5)
        • ETC (3)
      • Homebrew (0)
  • 블로그 메뉴

    • 홈
    • Introduce
    • 태그
    • 방명록
  • 링크

    • Naver Blog
    • Diary Blog
  • 공지사항

  • 인기 글

  • 태그

    mssql
    델파이
    개발환경
    소스코드
    기초
    VCL
    iis
    ASP.NET
    Python
    강좌
    SQL
    Web
    objectpascal
    JSON
    Flutter
    delphi
    프로그래밍
    웹프로그래밍
    C#
    문법
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.5
레이조(RayCho)
[PHP] MySQL 사용 기초 클래스(BasicMySQL)
상단으로

티스토리툴바