Encapsulate your own DB Class (PHP), Encapsulate DB Class php_php tutorial

Source: Internet
Author: User

Encapsulate your own DB Class (PHP), Encapsulate DB class PHP


encapsulates a DB class, which is used to operate the database specifically, and subsequent operations on the database are implemented by the DB Class object. This has its own DB class, write the project when the simple SQL statement does not have to write every time, direct call on the line, very convenient!

1. Encapsulate a DB class. A class file should have only one class, and none of the other content. naming rules for class files: class name. class.php

Here's the code to create the DB class:

 Php//encapsulates a DB class, which is used to operate the database specifically, and subsequent operations on the database are implemented by the DB Class object .    classdb{//Properties        Private $host; Private $port; Private $user; Private $pass; Private $dbname; Private $charset; Private $prefix;//Table Prefixes        Private $link;//Connecting resources (connecting to a database typically returns a resource, so you need to define a link property)//constructor Method (function: In order to initialize the object's properties), it will be automatically called        /** @param1 array $arr, default is empty, inside is an associative array, there are 7 elements * Array (' host ' = ' localhost ', ' port ' = ' 3306 '); */         Public function__construct ($arr=Array()){            //Initialize            $this->host =isset($arr[' Host ']) ?$arr[' Host ']: ' localhost ';//first determine if you have your own host, if you have to use your own host, otherwise you will use the default localhost            $this->port =isset($arr[' Port ']) ?$arr[' Port ']: ' 3306 '; $this->user =isset($arr[' User ']) ?$arr[' User ']: ' Root '; $this->pass =isset($arr[' Pass ']) ?$arr[' Pass ']: ' Root '; $this->dbname =isset($arr[' dbname ']) ?$arr[' dbname ']: ' MyDatabase '; $this->charset =isset($arr[' CharSet ']) ?$arr[' CharSet ']: ' UTF8 '; $this->prefix =isset($arr[' prefix ']) ?$arr[' prefix ']: '; //Connect to the database (the class is to manipulate the database, so connect to the database)            $this-Connect (); //Set character sets            $this-Setcharset (); //Select Database            $this-Setdbname (); }        /** Connect to database*/        Private functionConnect () {//MySQL Extended connection            $this->link =mysql_connect($this->host. ':' .$this->port,$this->user,$this-pass); //Judging Results            if(!$this-link) {                //The result is an error.//Violent handling, if the actual online project (production environment) must be written to the log file                Echo' Database connection error:
'; Echo' Error number '.Mysql_errno() . '
'; Echo' Error content '.Mysql_error() . '
'; Exit; } } /** Set Character sets*/ Private functionSetcharset () {//Set $this->db_query ("Set names {$this->charset} "); } /** Select Database*/ Private functionSetdbname () {$this->db_query ("Use {$this->dbname} "); } /** Add Data * @param1 string $sql, insert statement to execute * @return Boolean, successful return is auto-Grow ID, failure returns false*/ Public functionDb_insert ($sql){ //Send Data $this->db_query ($sql); //successful return self-increment ID return mysql_affected_rows() ?mysql_insert_id() :FALSE; } /** Delete Data * @param1 string $sql, DELETE statement to execute * @return Boolean, successfully returns the number of rows affected, failure returns false*/ Public functionDb_delete ($sql){ //Send SQL $this->db_query ($sql); //Judging Results return mysql_affected_rows() ?mysql_affected_rows() :FALSE; } /** Update Data * @param1 string $sql, UPDATE statement to execute * @return Boolean, successfully returns the number of rows affected, failure returns false*/ Public functionDb_update ($sql){ //Send SQL $this->db_query ($sql); //Judging Results return mysql_affected_rows() ?mysql_affected_rows() :FALSE; } /** Query: Query a record * @param1 string $sql, the SQL statement to query * @return Mixed, successfully returned an array, failed to return false*/ Public functionDb_getrow ($sql){ //Send SQL $res=$this->db_query ($sql); //Judgment return return mysql_num_rows($res) ?Mysql_fetch_assoc($res) :FALSE; } /** Query: Query multiple records * @param1 string $sql, the SQL statement to query * @return Mixed, successfully returned a two-dimensional array, failed to return false */ Public functionDb_getall ($sql){ //Send SQL $res=$this->db_query ($sql); //Judgment return if(mysql_num_rows($res)){ //Looping through $list=Array(); //Traverse while($row=Mysql_fetch_assoc($res)){ $list[] =$row; } //return return $list; } //returns false return FALSE; } /** mysql_query Error handling * @param1 string $sql, SQL statement required to execute * @return mixed, return all */ Private functionDb_query ($sql){ //Send SQL $res=mysql_query($sql); //Judging Results if(!$res){ //The result is an error.//Violent handling, if the actual online project (production environment) must be written to the log file Echo' Statement An error occurred:
'; Echo' Error number '.Mysql_errno() . '
'; Echo' Error content '.Mysql_error() . '
'; Exit; } //No Errors return $res; } //__sleep Method Public function__sleep () {//returns an array of properties that need to be saved return Array(' Host ', ' Port ', ' user ', ' Pass ', ' dbname ', ' charset ', ' prefix '); } //__wakeup Method Public function__wakeup () {//Connecting Resources $this-Connect (); //set the character set and select the database $this-Setcharset (); $this-Setdbname (); } /** Get the full table name*/ protected functionGettablename () {//full table name: Prefix + table name return $this->prefix.$this-table; } }//this DB class, generally does not write the destructor (does not release resources)

2. Use the DB class, but if you are using a class to create an object, you must ensure that the class is loaded into the code area. You can use a magic function to automate the loading of classes

Automatic loading : When a script file executes certain statements (instantiated), it needs to go to the code area to find the corresponding class, and if it cannot find the corresponding class file to be loaded by the auto-load function.

Magic Function :__autoload ()

For example, we need to use the DB class in the index.php page, then we can call directly, the specific code is as follows:

 
  PHP    // Use DB Class object to Access database    //Load class file    //include_once ' DB.class.php ';        If you want to use other classes, you need to load (so use the Magic function __autoload to implement automatic loading of classes)    //Display the Magic function __autoload    //Parameters: The name    of the class that needs to be loaded function __autoload ($a) {        // to load the corresponding class file in        if (is_file("$a. class.php")) {            include_once "$a. Class.php ";        }    }     // instantiation of    $db New DB (array(' dbname ' = ' mydatabase '));        

http://www.bkjia.com/PHPjc/1103327.html www.bkjia.com true http://www.bkjia.com/PHPjc/1103327.html techarticle encapsulate your own DB Class (PHP), encapsulate the DB Class PHP package A DB class, used to operate the database specifically, the subsequent operation of the database is the DB class of objects to implement. This has its own ...

  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.