>  기사  >  백엔드 개발  >  PHP 데이터베이스 처리 캡슐화 클래스

PHP 데이터베이스 처리 캡슐화 클래스

墨辰丷
墨辰丷원래의
2018-05-29 11:06:482347검색

이 글은 주로 PHP 데이터베이스 처리 캡슐화 클래스를 소개하고, mysqli 캡슐화를 기반으로 한 PHP의 데이터베이스 연결, 추가, 삭제, 수정 및 기타 작업을 완전한 예제 형식으로 분석합니다.

자세한 내용은 다음과 같습니다.

MySQL 연산 관련 클래스, mysqli를 확인하고 사용함

<?php
  //sample15_12.php
  class mydb {
    private $user;
    private $pass;
    private $host;
    private $db;
    //Constructor function.
    public function __construct (){
      $num_args = func_num_args();
      if($num_args > 0){
        $args = func_get_args();
        $this->host = $args[0];
        $this->user = $args[1];
        $this->pass = $args[2];
        $this->connect();
      }
    }
    //Function to tell us if mysqli is installed.
    private function mysqliinstalled (){
      if (function_exists ("mysqli_connect")){
        return true;
      } else {
        return false;
      }
    }
    //Function to connect to the database.
    private function connect (){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db = new mysqli ($this->host,$this->user,$this->pass)){
            $exceptionstring = "Error connection to database: <br />";
            $exceptionstring .= mysqli_connect_errno() . ": " . mysqli_connect_error();
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!$this->db = mysql_connect ($this->host,$this->user,$this->pass)){
            $exceptionstring = "Error connection to database: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to select a database.
    public function selectdb ($thedb){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db->select_db ($thedb)){
            $exceptionstring = "Error opening database: $thedb: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!mysql_select_db ($thedb, $this->db)){
            $exceptionstring = "Error opening database: $thedb: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to perform a query.
    public function execute ($thequery){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db->query ($thequery)){
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          } else {
            echo "Query performed correctly: " . $this->db->affected_rows . " row(s) affected.<br />";
          }
        //Mysql functionality.
        } else {
          if (!mysql_query ($thequery, $this->db)){
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          } else {
            echo "Query performed correctly: " . mysql_affected_rows () . " row(s) affected.<br />";
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to return a row set.
    public function getrows ($thequery){
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if ($result = $this->db->query ($thequery)){
            $returnarr = array ();
            while ($adata = $result->fetch_array ()){
              $returnarr = array_merge ($returnarr,$adata);
            }
            return $returnarr;
          } else {
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!$aquery = mysql_query ($thequery)){
            $exceptionstring = "Error performing query: $thequery: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          } else {
            $returnarr = array ();
            while ($adata = mysql_fetch_array ($aquery)){
              $returnarr = array_merge ($returnarr,$adata);
            }
            return $returnarr;
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
    //Function to close the database link.
    public function __destruct() {
      try {
        //Mysqli functionality.
        if ($this->mysqliinstalled()){
          if (!$this->db->close()){
            $exceptionstring = "Error closing connection: <br />";
            $exceptionstring .= $this->db->errno . ": " . $this->db->error;
            throw new exception ($exceptionstring);
          }
        //Mysql functionality.
        } else {
          if (!mysql_close ($this->db)){
            $exceptionstring = "Error closing connection: <br />";
            $exceptionstring .= mysql_errno() . ": " . mysql_error();
            throw new exception ($exceptionstring);
          }
        }
      } catch (exception $e) {
        echo $e->getmessage();
      }
    }
  }
  //Now, let us create an instance of mydb.
  $mydb = new mydb ("localhost","root","");
  //Select a database to use.
  $mydb->selectdb ("wps");
  //Now, let&#39;s perform an action.
  //$adata = $mydb->execute ("UPDATE cd SET title=&#39;Hybrid Theory&#39; WHERE cdid=&#39;2&#39;");
  //Then, let&#39;s try to return a row set.
  $adata = $mydb->getrows ("SELECT * FROM wp_terms");
  for ($i = 0; $i < count ($adata); $i++){
    echo $adata[$i] . "<br />";
  }
  $mydb->selectdb("test");
  $result = $mydb->execute("UPDATE user SET age = 23 WHERE id = 2");
  echo "<br />";
  echo $result;
?>

위 내용은 이 글의 전체 내용이므로, 모든 분들의 학습에 도움이 되기를 바랍니다.


관련 권장사항:

php는 PDO캡슐화 클래스자세한 예제

XML 작업을 기반으로 강력한 MYSQL을 구현합니다(캡슐화 클래스완전한 예제 분석

)

PHP 구현 DES 암호화 및 암호 해독 캡슐화 클래스 완전한 방법

위 내용은 PHP 데이터베이스 처리 캡슐화 클래스의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.