The encapsulation and use of PHP database classes

Source: Internet
Author: User
Tags php database
This article introduces the contents of the PHP database class packaging and use, has a certain reference value, now share to everyone, the need for friends can refer to

Encapsulation class
<?php//encapsulates a DB class, which is used to operate the database specifically, and all subsequent operations on the database are implemented by the DB Class object to implement the class db{//attribute private $host;        Private $port;        Private $user;       Private $pass;        Private $dbname;    Private $charset;            Private $prefix;                Table prefix private $link; Connecting the resource (connecting to the database typically returns a resource, so you need to define a link property)//constructor Method (function: To initialize the object's properties), will be automatically called/* * @param1 array $arr, default is empty, inside is          An associative array with 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 ']: ' CZYYZB '; $this->dbname = isset ($arr [' dbname '])?          $arr [' dbname ']: ' mydb ';   $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 to connect to the database) $this->connect ();             Sets the character set $this->setcharset ();         Select Database $this->setdbname (); }/* * Connect to Database */Private function connect () {//mysql Extended connection $th Is->link = mysql_connect ($this->host.        ':' .               $this->port, $this->user, $this->pass);                   Judging the result if (! $this->link) {//Result error//violence handling, if true online project (production environment) must be written to log file                   Echo ' Database connection error:<br/> '; Echo ' Error number '. Mysql_errno ().                   ' <br/> '; Echo ' ERROR content '. Mysql_error ().                   ' <br/> ';               Exit }/* * Set Character set */Private function SetCHarset () {//Set $this->db_query ("Set names {$this->charset}"); }/* * Select database */Private Function Setdbname () {$this->db_que            Ry ("Use {$this->dbname}"); }/* Add data * @param1 string $sql, insert statement to execute * @return Boolean, successful return is autogrow ID, Failure returns false */Public function Db_insert ($sql) {//Send data $this                  ->db_query ($sql); Successfully returned the self-increment ID return mysql_affected_rows ()?               MYSQL_INSERT_ID (): FALSE; }/* * Delete data * @param1 string $sql, DELETE statement to execute * @return Boolean, successful                   Returns the number of rows affected, Failure returns false */Public function Db_delete ($sql) {//Send SQL                   $this->db_query ($sql); Judgment result 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 function db_update ($sql) {//Send SQL                   $this->db_query ($sql); Judgment result return mysql_affected_rows ()?               Mysql_affected_rows (): FALSE; }/* Query: Query a record * @param1 string $sql, SQL statement to query * @return m                    Ixed, successfully returned an array, failed to return false */Public function Db_getrow ($sql) {//Send SQL                    $res = $this->db_query ($sql); Return mysql_num_rows ($res)?                MYSQL_FETCH_ASSOC ($res): FALSE; }/* Query: Query multiple records * @param1 string $sql, the SQL statement to query * @retu RN mixed, successfully returned a two-dimensional array, failedReturns false */Public function Db_getall ($sql) {//Send SQL                     $res = $this->db_query ($sql); Judgment return if (Mysql_num_rows ($res)) {//Loop traversal $list = Array ()                         ;                         Traverse while ($row = Mysql_fetch_assoc ($res)) {$list [] = $row;                     }//returns return $list;                  }//returns false to false;                   }/* * mysql_query error handling * @param1 string $sql, SQL statement to execute                      * @return mixed, as long as the statement does not go wrong, all return */Private function Db_query ($sql) {                      Send SQL $res = mysql_query ($sql);      Determine the result 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 errors occurred                          :<br/> '; Echo ' Error number '. Mysql_errno ().                          ' <br/> '; Echo ' ERROR content '. Mysql_error ().                          ' <br/> ';                      Exit                  }//No error 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 () {//Connection resource                      $this->connect ();                      Set character sets and select Database $this->setcharset ();                  $this->setdbname ();             }/* * Get the full table name */     protected function Gettablename () {//Full table name: Prefix + table name return $this->prefix. $                  this->table; }}?>



Use
<? Php
Header ("content-type:text/html; Charset=utf-8 "), Include (" conn.php ");//Instantiate $con = new DB (Array (' dbname ' = ' oilmis_wh ')); $sql =" SELECT * from stock "; $ arr = $con->db_getall ($sql);
? >//this DB class, generally does not write the destructor (does not release the resources)

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.