Php-encapsulated database functions and usage examples [refer to thinkPHP]

Source: Internet
Author: User
This article mainly introduces php-encapsulated database functions and usage. it is simplified based on the database operation code in thinkPHP, including database settings, connections, queries, and log operations, simple and practical. if you need it, you can refer to the example in this article to describe the php-encapsulated database functions and usage. We will share this with you for your reference. The details are as follows:

The database module extracted from Thinkphp is very useful.

Common. php:

 '. $ Label. htmlspecialchars ($ output, ENT_QUOTES ).'
';} Else {$ output = $ label. print_r ($ var, true) ;}} else {ob_start (); var_dump ($ var); $ output = ob_get_clean (); if (! Extension_loaded ('xdebug') {$ output = preg_replace ("/\] \=\> \ n (\ s +)/m", '] => ', $ output); $ output ='
' . $label . htmlspecialchars($output, ENT_QUOTES) . '
';}} If ($ echo) {echo ($ output); return null;} else return $ output ;} /*** debug output ** @ param type $ msg */function _ debug ($ msg) {if (C ("debug") echo "$ msg
";} Function _ log ($ filename, $ msg) {$ time = date (" Y-m-d H: I: s "); $ msg = "[$ time] \ n $ msg \ r \ n"; if (C ("log") {$ fd = fopen ($ filename, "a +"); fwrite ($ fd, $ msg); fclose ($ fd );}} /*** log record * @ param type $ str */function L ($ msg) {$ time = date ("Y-m-d H: I: s "); $ clientIP = $ _ SERVER ['remote _ ADDR ']; $ msg = "[$ time $ clientIP] $ msg \ r \ n "; $ log_file = C ("LOGFILE"); _ log ($ log_file, $ msg);}?>

Config. php:

 'Mysql', 'DB _ host' => '127. 0.0.1 ', 'DB _ name' => 'DB', 'DB _ user' => 'user', 'DB _ pwd' => 'pwd ', 'db _ port' => '123',); return $ DB;?>

Database Model class Model. class. php, put it in the classes/directory:

 Db = $ this-> connect ();}/*** database connection method */public function connect ($ config = '', $ linkNum = 0) {if (! Isset ($ this-> linkID [$ linkNum]) {if (empty ($ config )) $ config = array ('username' => C ('Db _ user'), 'password' => C ('Db _ pwd '), 'hostname' => C ('Db _ host'), 'hostport' => C ('Db _ Port '), 'database' => C ('Db _ name'); $ this-> linkID [$ linkNum] = new mysqli ($ config ['hostname'], $ config ['username'], $ config ['password'], $ config ['database'], $ config ['hostport']? Intval ($ config ['hostport']): 3306); if (mysqli_connect_errno () throw_exception (mysqli_connect_error (); $ this-> connected = true ;} return $ this-> linkID [$ linkNum];}/*** initialize database connection */protected function initConnect () {if (! $ This-> connected) {$ this-> db = $ this-> connect ();}} /*** obtain all query data * @ access private * @ param string $ SQL statement * @ return array */public function select ($ SQL) {$ this-> initConnect (); if (! $ This-> db) return false; $ query = $ this-> db-> query ($ SQL); $ list = array (); if (! $ Query) return $ list; while ($ rows = $ query-> fetch_assoc () {$ list [] = $ rows;} return $ list ;} /*** query only one data entry */public function find ($ SQL) {$ resultSet = $ this-> select ($ SQL); if (false ===$ resultSet) {return false;} if (empty ($ resultSet) {// The query result is empty return null;} $ data = $ resultSet [0]; return $ data ;} /*** obtain the field value of a record. the SQL statement is organized by the user. * example: $ model-> getField ("select id from user limit 1") */publ Ic function getField ($ SQL) {$ resultSet = $ this-> select ($ SQL); if (! Empty ($ resultSet) {return reset ($ resultSet [0]);}/*** run the query to return the dataset */public function query ($ str) {$ this-> initConnect (); if (! $ This-> db) {if (C ("debug") echo "connect to database error"; return false ;}$ this-> queryStr = $ str; // release the previous query result if ($ this-> queryID) $ this-> free (); $ this-> queryID = $ this-> db-> query ($ str); // improves the stored procedure if ($ this-> db-> more_results ()) {while ($ res = $ this-> db-> next_result ())! = NULL) {$ res-> free_result () ;}// $ this-> debug (); if (false ===$ this-> queryID) {echo $ this-> error (); return false;} else {$ this-> numRows = $ this-> queryID-> num_rows; $ this-> numCols = $ this-> queryID-> field_count; return $ this-> getAll () ;}/ *** execute a statement, such as insert, UPDATE operation * @ access public * @ param string $ str SQL command * @ return integer */public function execute ($ str) {$ this-> initConnect (); if (! $ This-> db) return false; $ this-> queryStr = $ str; // release the previous query result if ($ this-> queryID) $ this-> free (); $ result = $ this-> db-> query ($ str); if (false = $ result) {$ this-> error (); return false;} else {$ this-> numRows = $ this-> db-> affected_rows; $ this-> lastInsID = $ this-> db-> insert_id; return $ this-> numRows ;}} /*** obtain all query data * @ access private * @ param string $ SQL statement * @ return array */private function GetAll () {// return dataset $ result = array (); if ($ this-> numRows> 0) {// return dataset for ($ I = 0; $ I <$ this-> numRows; $ I ++) {$ result [$ I] = $ this-> queryID-> fetch_assoc ();} $ this-> queryID-> data_seek (0);} return $ result;}/*** return the last inserted ID */public function getLastInsID () {return $ this-> db-> insert_id;} // return the final executed SQL statement public function _ SQL () {return $ this-> queryStr ;} /*** database error message */public function error () {$ This-> error = $ this-> db-> errno. ':'. $ this-> db-> error; if (''! = $ This-> queryStr) {$ this-> error. = "\ n [SQL statement]:". $ this-> queryStr;} // trace ($ this-> error, '', 'err'); return $ this-> error ;} /*** release query result */public function free () {$ this-> queryID-> free_result (); $ this-> queryID = null ;} /*** close database */public function close () {if ($ this-> db) {$ this-> db-> close ();} $ this-> db = null;}/*** destructor */public function _ destruct () {if ($ this-> queryID) {$ this-> free () ;}// close the connection $ this-> close ();}}

Example:

#include "common.php"function test(){ $model = M(); $sql = "select * from test"; $list = $model->query($sql); _dump($list);}

I hope this article will help you with PHP programming.

For more php-encapsulated database functions and usage examples, see thinkPHP. For more information, see PHP!

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.