PHP Data operation class & lt ;? Php ** + ---------------------- * Mysql operation class + ---------------------- * file name Db. class. php + ---------------------- * file description mysql operation class + -------------------- * classDb {PHP Data operation class
CachePath. strtoupper (md5 ($ fileName )). ". ". $ this-> cacheFileExt; $ this-> cacheFileName = $ cacheFileName;}/** generate a cache file name based on the current dynamic file */function getCacheFileName () {return $ this-> cacheFileName ;} /*** connect to the database ** @ access public * @ param array $ db database configuration * @ return resource database connection id */public function connect ($ db) {// use different functions to connect to the database according to the configuration $ db ['host'] = isset ($ db ['port'])? $ Db ['host']. ':'. $ db ['port']: $ db ['host']; $ db ['char '] = isset ($ db ['char'])? $ Db ['char ']: $ this-> dbCharset; $ func = $ db ['pconnect']? 'MySQL _ pconnect ': 'MySQL _ connect'; $ this-> link = $ func ($ db ['host'], $ db ['user'], $ db ['pwd']); mysql_select_db ($ db ['database'], $ this-> link ); mysql_query ("set names '{$ db ['char']} '"); $ this-> cachePath = isset ($ db ['cachepath'])? $ Db ['cachepath']: $ this-> cachepath; return $ this-> link ;} /*** query a qualified record ** @ access public * @ param string $ where query condition * @ param string $ field query field * @ param string $ table *@ return mixed matching record */public function find ($ where = NULL, $ field = '*', $ table = '') {return $ this-> findAll ($ where = NULL, $ field = '*', $ table = '', FALSE);}/*** query all records that meet the conditions ** @ access public * @ param string $ where Query condition * @ param string $ field query field * @ param string $ table * @ return mixed matching record */public function findAll ($ where = NULL, $ field = '*', $ table = '', $ all = TRUE) {$ this-> options ['where'] = is_null ($ where )? @ $ This-> options ['where']: $ where; $ this-> options ['field'] = isset ($ this-> options ['field'])? $ This-> options ['field']: $ field; $ this-> options ['table'] = $ table = ''? $ This-> table: $ table; $ SQL = "SELECT {$ this-> options ['field']} FROM '{$ this-> options ['table']}'"; $ SQL. = isset ($ this-> options ['join'])? 'Left join'. $ this-> options ['join']: ''; $ SQL. = isset ($ this-> options ['where'])? 'Where'. $ this-> options ['where']: ''; $ SQL. = isset ($ this-> options ['group'])? 'Group by'. $ this-> options ['group']: ''; $ SQL. = isset ($ this-> options ['having'])? 'Having '. $ this-> options ['having']: ''; $ SQL. = isset ($ this-> options ['order'])? 'Order by'. $ this-> options ['order']: ''; $ SQL. = isset ($ this-> options ['limit'])? 'Limit '. $ this-> options ['limit']: ''; $ this-> SQL = $ SQL; $ row = NULL; // If cache is enabled, if ($ this-> cache = TRUE) {$ this-> setCacheFileName ($ this-> SQL ); $ row = $ this-> readCache ();} // if the Read fails, or the cache is not enabled if (is_null ($ row )) {$ result = $ this-> query (); $ row = $ all === TRUE? $ This-> fetchAll ($ result): $ this-> fetch ($ result); // If cache is enabled, write if ($ this-> cache = TRUE) {$ this-> writeCache ($ row) ;}$ this-> options = array ();} return $ row ;} /*** READ all records in the result set to the array ** @ access public * @ param resource $ result set * @ return array */public function fetchAll ($ result = NULL) {$ rows = array (); while ($ row = $ this-> fetch ($ result) {$ rows [] = $ row;} return $ rows ;} /*** read a row in the result set Record to the array ** @ access public * @ param resource $ result set * @ param int $ type return type, 1 is an array, 2: The object * @ return mixed returns */public function fetch ($ result = NULL, $ type = NULL) {$ result = is_null ($ result )? $ This-> result: $ result; $ type = is_null ($ type )? $ This-> returnType: $ type; $ func = $ type = 1? 'MySQL _ fetch_assoc ': 'MySQL _ fetch_object'; return $ func ($ result );} /*** run the SQL command ** @ access public * @ param string $ SQL SQL command * @ param resource $ link database connection id * @ return mixed database result set */public function query ($ SQL = '', $ link = NULL) {$ SQL = empty ($ SQL )? $ This-> SQL: $ SQL; $ link = is_null ($ link )? $ This-> link: $ link; $ this-> result = mysql_query ($ SQL, $ link); if (is_resource ($ this-> result )) {return $ this-> result;} // if an error occurs during SQL execution, an exception exit ('Mysql error:'. $ This-> getError ());} /*** run the SQL command ** @ access public * @ param string $ SQL SQL command * @ param resource $ link database connection id * @ return bool whether execution is successful */public function execute ($ SQL = '', $ link = NULL) {$ SQL = empty ($ SQL )? $ This-> SQL: $ SQL; $ link = is_null ($ link )? $ This-> link: $ link; if (mysql_query ($ SQL, $ link) {return TRUE;} return FALSE ;} /***** insert record ** @ access public * @ param array $ data insert record. Format: array ('field name' => 'value ', 'Field name' => 'value'); * @ param string $ table name * @ return bool current record id */public function add ($ data, $ table = NULL) {$ table = is_null ($ table )? $ This-> table: $ table; $ SQL = "INSERT INTO '{$ table}'"; $ fields = $ values = array (); $ field = $ value = ''; // traverse the record and format the field name and value foreach ($ data as $ key => $ val) {$ fields [] = "'{$ table }'. '{$ key}' "; $ values [] = is_numeric ($ val )? $ Val: "'{$ val}'";} $ field = join (',', $ fields); $ value = join (',', $ values ); unset ($ fields, $ values); $ SQL. = "({$ field}) VALUES ({$ value})"; $ this-> SQL = $ SQL; $ this-> execute (); return $ this-> insertId ();} /*** delete record ** @ access public * @ param string $ where condition * @ param string $ table name * @ return bool affects the number of rows */public function delete ($ where = NULL, $ table = NULL) {$ table = is_null ($ table )? $ This-> table: $ table; $ where = is_null ($ where )? @ $ This-> options ['where']: $ where; $ SQL = "DELETE FROM '{$ table}' where {$ WHERE }"; $ this-> SQL = $ SQL; $ this-> execute (); return $ this-> affectedRows ();} /***** UPDATE record ** @ access public * @ param array $ data: array ('field name' => value ); * @ param string $ where update condition * @ param string $ table name * @ return how many messages are affected by bool */public function update ($ data, $ where = NULL, $ table = NULL) {$ table = is_null ($ table )? $ This-> table: $ table; $ where = is_null ($ where )? @ $ This-> options ['where']: $ where; $ SQL = "update' {$ table} 'set"; $ values = array (); foreach ($ data as $ key => $ val) {$ val = is_numeric ($ val )? $ Val: "'{$ val}'"; $ values [] = "'{$ table }'. '{$ key}' = {$ val} ";} $ value = join (',', $ values); $ this-> SQL = $ SQL. $ value. "WHERE {$ where}"; $ this-> execute (); return $ this-> affectedRows ();} /*** read cache ** @ access public * @ return mixed the cached content is returned if the read is successful. otherwise, NULL */protected function readCache () is returned () {$ file = $ this-> getCacheFileName (); if (file_exists ($ file) {// cache expiration if (filemtime ($ file) + $ this-> cacheLimitTime) <time () {@ unlink ($ file); return NULL;} if (1 ===$ this-> returnType) {$ row = include $ file ;} else {$ data = file_get_contents ($ file); $ row = unserialize ($ data);} return $ row;} return NULL ;} /***** write cache ** @ access public * @ param mixed $ data cache content * @ return bool write successful */public function writeCache ($ data) {$ file = $ this-> getCacheFileName (); if ($ this-> makeDir (dirname ($ file) {if (1 ===$ this-> returnType) {$ data ='
';} Else {$ data = serialize ($ data) ;}} return file_put_contents ($ file, $ data );} /** Clear cache file * string $ fileName specify the file name (including the function) or all (all) * Returns true if the file is cleared successfully, otherwise, false */function compute ache ($ fileName = "all") {if ($ fileName! = "All") {if (file_exists ($ fileName) {return @ unlink ($ fileName);} else return false;} if (is_dir ($ this-> cachePath )) {if ($ dir = @ opendir ($ this-> cachePath) {while ($ file = @ readdir ($ dir) {$ check = is_dir ($ file ); if (! $ Check) @ unlink ($ this-> cachePath. $ file) ;}@ closedir ($ dir); return true ;}else {return false ;}} else {return false ;}} /** create a directory consecutively * string $ dir directory string * int $ mode permission number * Returns true if the directory is successfully created or all directories are created, otherwise, false */function makeDir ($ dir, $ mode = "0777") {if (! $ Dir) return 0; $ dir = str_replace ("\", "/", $ dir); $ mdir = ""; foreach (explode ("/", $ dir) as $ val) {$ mdir. = $ val. "/"; if ($ val = ".. "| $ val = ". "| trim ($ val) =" ") continue; if (! File_exists ($ mdir) {if ([email protected] ($ mdir, $ mode) {return false ;}} return true ;}// automatically load the function, implement special public function _ call ($ func, $ args) {if (in_array ($ func, array ('field', 'join', 'where ', 'order', 'group', 'limit', 'having ') {$ this-> options [$ func] = array_shift ($ args); return $ this ;} elseif ($ func === 'table') {$ this-> options ['table'] = array_shift ($ args); $ this-> table = $ this-> option S ['table']; return $ this;} // if the function does not exist, an exception exit ('Call to undefined method Db ::'. $ func. '()');} // ------------------------------------------- // returns the number of rows affected by the previous operation. public function affectedRows ($ link = null) {$ link = is_null ($ link )? $ This-> link: $ link; return mysql_affected_rows ($ link);} // return the id of the last operation record public function insertId ($ link = null) {$ link = is_null ($ link )? $ This-> link: $ link; return mysql_insert_id ($ link);} // clear the result set public function free ($ result = null) {$ result = is_null ($ result )? $ This-> result: $ result; return mysql_free_result ($ result);} // return error message public function getError ($ link = NULL) {$ link = is_null ($ link )? $ This-> link: $ link; return mysql_error ($ link);} // return error code public function getErrno ($ link = NULL) {$ link = is_null ($ link )? $ This-> link: $ link; return mysql_errno ($ link) ;}}?>
? Call method:
Connect ($ config); // input the configuration and connect to the database. $ link indicates the connection id $ rows = $ db-> table ('test')-> field ('*') -> order ('Id DESC ')-> limit (0, 10)-> findAll (); // The preceding operation is equivalent to executing the SQL command: SELECT * FROM test order by id desc limit 0, 10; print_r ($ db-> getCacheFileName ()); // $ db-> revoke ache ($ db-> getCacheFileName (); // $ db-> revoke ache (); // The execution result is the same as the preceding one, however, when a cache method is added, the cache () for this query has three parameters: cache (cache name, effective time, and cache path ); by default, the cache name uses md5 (SQL command) as the name, and the validity period is 1 minute by default. Clock, cache path can be configured when connecting to the database // Insert a record $ data = array ('name' => 'xiaokai ', 'pass' => '20140901',); $ db-> add ($ data ); // A record is inserted. Note that $ data is in the format of array ('field name 1' => 'value 1 ', 'Field name 2' => 'value 2 ',.....); // equivalent to executing the SQL command: INSERT INTO test ('name', 'pass') VALUES ('xiaokai', '123'); // friends may be surprised, the add function has not passed in the table name. why is this SQL command executed? // Actually, the $ db-> table ('test') method has been used for the above query. The table name has been input here, therefore, you do not need to specify the table name during the operation. // if there is an insert, there will be a delete. Next, delete $ db-> delete ('Id = 10 '); // DELETE the record with the id of 10 in the test table. // equivalent to executing the SQL command: DELETE FROM test WHERE id = 10; // The same is true here. the table name is not input. // The array is constructed below, and a record $ data = array ('name' => '123' is updated ', 'pass' => 'xiaokai',); $ db-> update ($ data, 'id = 10 '); // in this way, the record with id 10 is updated. // equivalent to executing the SQL command: UPDATE test set name = '000000', pass = 'xiaokai' WHERE id = 10;
?