Php-encapsulated database functions and usage examples [Refer to thinkPHP] And thinkphp example
This example describes 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:
<? PHP/*** common function * // contains the configuration file if (is_file ("config. php") {C (include 'config. php');} if (! Function_exists ("_ autoload") {function _ autoload ($ class_name) {require_once ('classes /'. $ class_name. '. class. php ') ;}}/*** database operation function * @ return \ mysqli */function M () {$ db = new Model (); if (mysqli_connect_errno ()) throw_exception (mysqli_connect_error (); return $ db;} // obtain the configuration value function C ($ name = null, $ value = null) {// static global variable, the subsequent values are all obtained in the $) config array static $ _ config = array (); // if no parameter exists, all if (em) Pty ($ name) return $ _ config; // get or assign values to if (is_string ($ name) {if (! Strpos ($ name, '.') {$ name = strtolower ($ name); if (is_null ($ value) return isset ($ _ config [$ name])? $ _ Config [$ name]: null; $ _ config [$ name] = $ value; return;} // supports $ name = explode ('. ', $ name); $ name [0] = strtolower ($ name [0]); if (is_null ($ value )) return isset ($ _ config [$ name [0] [$ name [1])? $ _ Config [$ name [0] [$ name [1]: null; $ _ config [$ name [0] [$ name [1] = $ value; return;} // set if (is_array ($ name) in batches )) {return $ _ config = array_merge ($ _ config, array_change_key_case ($ name);} return null; // avoid invalid parameters} function ajaxReturn ($ data = null, $ message = "", $ status) {$ ret = array (); $ ret ["data"] = $ data; $ ret ["message"] = $ message; $ ret ["status"] = $ status; echo json_encode ($ ret); die ();} // debug Array function _ dump ($ var) {if (C ("debug") dump ($ var);} // browser-friendly variable output function dump ($ var, $ echo = true, $ label = null, $ strict = true) {$ label = ($ label = null )? '': Rtrim ($ label).''; if (! $ Strict) {if (ini_get ('html _ errors ') {$ output = print_r ($ var, true); $ output =' <pre> '. $ label. htmlspecialchars ($ output, ENT_QUOTES ). '</pre>';} 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 = '<pre> '. $ label. htmlspecialchars ($ output, ENT_QUOTES ). '</pre>' ;}}if ($ echo) {echo ($ output); return null;} else return $ output ;} /*** debug output ** @ param type $ msg */function _ debug ($ msg) {if (C ("debug ")) echo "$ msg <br/>";} 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:
<? Php/*** Database Configuration File */$ db = array ('db _ type' => 'mysql', 'db _ host' => '2017. 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:
<? Php/*** database Model class */class Model {// database connection ID supports multiple connections protected $ linkID = array (); // The current database operation object protected $ db = null; // The current query ID protected $ queryID = null; // The current SQL command protected $ queryStr = ''; // whether the database has been connected to protected $ connected = false; // returns or affects the number of records protected $ numRows = 0; // The number of returned fields protected $ numCols = 0; // recent error message protected $ error = ''; public function _ construct () {$ this-> 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);}