Encapsulate your own DB class (PHP) and db class php

Source: Internet
Author: User
Tags autoload

Encapsulate your own DB class (PHP) and db class php

Encapsulate a DB class for database operations. All operations on the database in the future will be implemented by DB class objects. In this way, with your own DB class, you do not need to write a simple SQL statement every time when writing a project, just call it directly, which is very convenient!

1. encapsulate a DB class. A class file should have only one class, and no other content exists. Naming rules for class files: class Name. class. php

The following code creates a DB class:

<? Php // encapsulate a DB class for database operations. All operations on the database in the future will be performed by the DB class object to implement class DB {// attribute private $ host; private $ port; private $ user; private $ pass; private $ dbname; private $ charset; private $ prefix; // table prefix private $ link; // connect to resources (connect to the database, generally, a resource is returned, so you need to define a link attribute) // The Constructor (function: to initialize the object attribute) will be automatically called/** @ param1 array $ arr, the default value is null. It is an associated array with seven elements * array ('host' => 'localhost', 'Port' => '123 '); */public function _ construct ($ arr = arr Ay () {// initialize $ this-> host = isset ($ arr ['host'])? $ Arr ['host']: 'localhost'; // first, determine whether your host exists. If yes, use your host, otherwise, use the default localhost $ this-> port = isset ($ arr ['Port'])? $ Arr ['Port']: '000000'; $ 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 operate the database, so you need to connect to the database) $ this-> connect (); // set the character set $ this-> setCharset (); // select database $ this-> setDbname ();}/** connect to database */private function connect () {// mysql extended connection $ this-> link = mysql_connect ($ this-> host. ':'. $ this-> port, $ this-> user, $ this-> pass); // if (! $ This-> link) {// error in result // brute force processing. If a real online project (production environment) must be written to the 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_query ("use {$ this-> dbname}");}/** add data * @ param1 string $ SQL, insert statement to be executed * @ return B Oolean: The returned result is an Automatically increasing ID. If it fails, FALSE */public function db_insert ($ SQL) is returned. {// send data $ this-> db_query ($ SQL ); // return the auto-increment ID return mysql_affected_rows ()? Mysql_insert_id (): FALSE;}/** delete data * @ param1 string $ SQL, the delete statement to be executed * @ return Boolean, the number of affected rows is returned successfully, return FALSE */public function db_delete ($ SQL) {// send SQL $ this-> db_query ($ SQL); // return mysql_affected_rows ()? Mysql_affected_rows (): FALSE;}/** update data * @ param1 string $ SQL, the update statement to be executed * @ return Boolean, the number of affected rows is returned successfully, FALSE */public function db_update ($ SQL) {// send SQL $ this-> db_query ($ SQL); // return mysql_affected_rows ()? Mysql_affected_rows (): FALSE;}/** query: query a record * @ param1 string $ SQL. The SQL statement to be queried * @ return mixed. An array is returned successfully, return FALSE */public function db_getRow ($ SQL) {// send SQL $ res = $ this-> db_query ($ SQL ); // determine whether return mysql_num_rows ($ res) is returned )? Mysql_fetch_assoc ($ res): FALSE;}/** query: Query multiple records * @ param1 string $ SQL, the SQL statement to be queried * @ return mixed, A two-dimensional array is returned successfully, and FALSE */public function db_getAll ($ SQL) {// send SQL $ res = $ this-> db_query ($ SQL ); // determine if (mysql_num_rows ($ res) {// looping $ list = array (); // traversing while ($ row = mysql_fetch_assoc ($ res )) {$ list [] = $ row;} // return $ list;} // return FALSE;}/** mysql_query error handling * @ param1 string $ sq L. The SQL statement * @ return mixed to be executed. If no error occurs in the statement, all SQL statements */private function db_query ($ SQL) are returned) {// send SQL $ res = mysql_query ($ SQL); // determine the result if (! $ Res) {// error in the result // brute force processing. If a real online project (production environment) must be written to the log file echo, the following error occurs: <br/> '; echo 'error number '. mysql_errno (). '<br/>'; echo 'error content '. mysql_error (). '<br/>'; exit;} // No error return $ res;} // _ sleep method public function _ sleep () {// return the array return array ('host', 'Port', 'user', 'pass', 'dbname', 'charset ', 'prefix');} // _ wakeup method public function _ wakeup () {// connection resource $ this-> connect (); // set the character set and select the database $ this-> setCharset (); $ this-> setDbname ();}/** get the complete table name */protected function getTableName () {// complete table name: prefix + Table Name return $ this-> prefix. $ this-> table ;}/// this DB class. Generally, no destructor is written (resources are not released)

2. Use the DB class. To create an object using a class, make sure that the class has been loaded into the code area. You can use oneMagic FunctionsTo automatically load classes.

Automatic Loading: When a script file executes some statements (instantiation), it needs to find the corresponding class in the code area. If it cannot be found, it will load the corresponding class file by automatically loading the function.

Magic Functions:__ Autoload ()

For example, if we need to use the DB class on the index. php page, we can call it directly. The specific code is as follows:

<? Php // use the database class object to access the database // load the class file first // include_once 'DB. class. php '; // if you want to use other classes, you need to load them (so use the magic function _ autoload to automatically load classes) // display write magic function _ autoload // parameter: name of the class to be loaded function _ autoload ($) {// load the corresponding class file into if (is_file ("$. class. php ") {include_once" $. class. php ";}}// instantiate $ db = new DB (array ('dbname' => 'mydatabase '));

 

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.