Php database operation class (to add, delete, modify, and query tables, retrieve rows, and query multiple data Records)

Source: Internet
Author: User
Php database operation class (to add, delete, modify, and query tables, retrieve rows, and query multiple data Records)
The php database operation class allows you to add, delete, modify, and query tables, obtain the number of rows, query multiple data records, query left connections, and create a data table structure. Rich functions to facilitate value shifting. if you have any need, refer.

Complete php database code and examples are as follows.

1. code

     Links = mysql_connect (DB_HOST, DB_USER, DB_PWD); if (DEBUG) {mysql_select_db (DB_NAME) or die ('Error :'. mysql_error ();} else {mysql_select_db (DB_NAME);} $ char_ SQL = "SET NAMES '". CHARSET. "'"; $ this-> query ($ char_ SQL );} ***************** ** // ** add, delete, modify, and query operation method * enter an SQL statement * to return a Boolean value or result set $ row */function query ($ SQL) {if (DEBUG) {$ render = mysql_query ($ SQL) or die ('query ERROR :'. mysql_error ()."
SQL statement error :". $ SQL); return $ render;} else {return mysql_query ($ SQL) ;}}/*** input * result array */function count ($ table, $ condition = '1') {$ SQL = "select count (*) from '". DB_PREFIX. $ table. "'Where $ condition"; $ result = $ this-> select ($ SQL); return $ result [0] ['count (*) '];} /*** original SQL statement query operation method * input SQL statement * result array */function select ($ SQL) {$ row = $ this-> query ($ SQL ); $ results = array (); while ($ arr = $ this-> fetch ($ row) {$ resul Ts [] = $ arr;} // $ this-> free_result ($ row); return $ results ;} /*** check whether a field has a value * @ param input table name. field, value * @ return id or false **/function check_exists ($ table, $ val) {$ render = false; $ tab = explode ('. ', $ table); if ($ tab ['1'] & $ tab ['1']! = 'Id') {$ fields = $ tab ['1']; $ table = "{$ tab [0]}. id, {$ fields} ";} else {$ fields = 'id'; $ table = $ tab [0]. ". id ";}$ condition =" '$ fields' = '{$ val}' "; $ detail = $ this-> read ($ table, $ condition ); if ($ detail [$ fields]) {$ render = $ detail ['id'];} return $ render ;} /*** query multiple data methods * input table name. field, field; query condition, number of items * if the condition is an array, enter the advanced search mode * returned result array */function readall ($ table, $ condition = '1 ', $ limit = '') {$ tab = explode ('. ', $ table); $ table = $ tab ['0']; if ($ tab ['1']) {$ fields = $ tab ['1']; $ fields_array = explode (',', $ fields); $ fields = ''; foreach ($ fields_array as $ one) {$ fields. = "'$ one'," ;}$ fields = rtrim ($ fields,', ');} else {$ fields = '*';} if (is_array ($ condition) {$ condition = $ this-> parse_condition ($ condition);} $ SQL = "select $ fields from '". DB_PREFIX. $ table. "'Where $ condition"; if ($ limit) $ SQL. = "limit $ limit"; return $ this-> select ($ SQL);}/*** query a single data method * input table name. field, field; query condition * returned result array */function read ($ table, $ condition = '1') {$ render = $ this-> readall ($ table, $ condition, 1); return $ render [0];}/*** modify data method * input table name, insert data array ('field' => 'value '), condition * returns a boolean value */function update ($ table, $ data, $ condition) {$ set = ''; foreach ($ data as $ key => $ val) {$ set. = "'$ key' = '". $ val. "'," ;}$ set = rtrim ($ set,', '); if (is_array ($ condition )) {$ condition = $ this-> parse_condition ($ condition);} $ SQL = "update '". DB_PREFIX. $ table. "'set $ set where $ condition"; return $ this-> query ($ SQL);}/*** data insertion method * name of the input table, data array ('field' => 'value') * returns Boolean */function insert ($ table, $ data) {$ fields = array (); $ values = array (); foreach ($ data as $ key => $ val) {if (is_array ($ val) {$ _ values = array (); $ _ fields = array (); foreach ($ val as $ k = >$ v) {$ _ fields [] = "'$ k '"; $ _ values [] = "'{$ v}'" ;}$ fields =$ _ fields; $ values [] = '('. implode (',', $ _ values ). ')';} else {$ fields [] = "'$ key'"; $ values [] = "' {$ val }'";}} $ fields = implode (',', $ fields); $ values = implode (',', $ values); $ SQL = "insert '". DB_PREFIX. $ table. "'($ fields) values ($ values)"; return $ this-> query ($ SQL);}/***** data deletion method * name of the input table, condition * return bool */function delete ($ table, $ condition) {if (empty ($ condition) {die ('condition cannot be blank ');} if (is_array ($ condition) {$ condition = $ this-> parse_condition ($ condition);} $ SQL = "delete from '". DB_PREFIX. $ table. "'Where $ condition"; return $ this-> query ($ SQL);}/*** resolution condition function * @ param condition array *$arr[] = "`id`==0";$arr[] = "`id`==5";$arr['id'] = "5";$arr['or'][] = "`id`!=2";$arr['or'][] = "`id`!=1";$arr['or'][] = "`id`!=2";$arr['groups'][]='id';$arr['orders']['id']='asc';$arr['orders']['td']='DESC';* * @ Return str **/function parse_condition ($ condition) {$ and = '1'; $ or = '0'; $ groups = array (); $ orders = array (); foreach ($ condition as $ key => $ val) {if (is_numeric ($ key) {$ and. = "and $ val";} elseif (strtolower ($ key) = 'or') {// process or condition if (is_array ($ val )) {foreach ($ val as $ k =>$ v) {if (is_numeric ($ k) {$ or. = "or {$ v}";} elseif (is_array ($ v) {$ v = implode (',', $ v); $ or. = "or '$ k' in ($ v)";} else {$ or. = "or '$ k = '{ $ V} '";}}} else {$ or. = "or $ val '" ;}} elseif (strtolower ($ key) = 'groupup') {// process group byforeach ($ val as $ k => $ v) {$ groups [] = $ v ;}} elseif (strtolower ($ key) = 'orders ') {// process order byforeach ($ val as $ k => $ v) {$ orders [] = $ k. ''. $ v ;}} else {if (is_array ($ val) {$ val = implode (',', $ val); $ and. = "and '$ key' in ($ val)";} else {$ and. = "and '$ key' =' {$ val} '" ;}}} if ($ and! = '1' & $ or! = '0') $ where = $ and. 'or'. $ or; elseif ($ and! = '1') $ where = $ and; elseif ($ or! = '0') $ where = $ or; if ($ groups) $ where. = "group ". implode (',', $ groups); if ($ orders) $ where. = "order ". implode (',', $ orders); $ where = str_replace ('1 and ', '', str_replace ('0 or','', $ where )); return $ where;}/*** lock table method * name of the input table, lock type, r or w write lock should be placed before the read lock * return bool */function lock ($ table, $ type = 'r') {if ($ type = 'r') {$ type = 'read';} else {$ type = 'write ';} $ SQL = "lock table '". DB_PREFIX. $ table. "'$ type"; return $ this -> Query ($ SQL);}/** unlock table method ** return bool */function unlock () {$ SQL = "unlock tables "; return $ this-> query ($ SQL);}/*** put result set into array method * return array, Pointer down */function fetch ($ row) {return mysql_fetch_array ($ row, MYSQL_ASSOC);}/*** method for calculating the number of rows in the result set * input $ row * Number of returned rows */function num_rows ($ row) {return mysql_num_rows ($ row);}/*** calculation result set columns method * input $ row * returned columns */function num_fields ($ row) {return mysql_num_fields ($ row);}/*** release result set memory * return boolean value */fu Nction free_result ($ row) {return mysql_free_result ($ row );} /*** view the field name of the specified table * input table name * returns an array of all field names */function list_fields ($ table) {$ fields = mysql_list_fields (DB_NAME, DB_PREFIX. $ table, $ this-> links); $ columns = mysql_num_fields ($ fields); for ($ I = 0; $ I <$ columns; $ I ++) {$ row [$ I] = mysql_field_name ($ fields, $ I);} return $ row;}/*** method for viewing database versions */function version () {return mysql_get_server_info ();}/*** view the insert ID during insertion * /Function insert_id () {return mysql_insert_id ();}/*** paging method */function page ($ table, $ condition = '1', $ pagesize = 20, $ id = 'page') {$ page =$ _ GET [$ id]; if (! $ Page) $ page = 0; elseif (! Is_numeric ($ page) die ('Paging error'); // query result set $ p = $ page * $ pagesize; $ limit = $ p. ",". $ pagesize; $ results = $ this-> readall ($ table, $ condition, $ limit); // get the number of rows in the result set $ num = $ this-> count ($ table, $ condition); // defines the last page $ maxpageif ($ num % $ pagesize) {$ maxpage = (int) ($ num/$ pagesize + 1 );} else $ maxpage = $ num/$ pagesize; if (STATICS) {// obtain url information from the server if ($ _ GET [$ id] === null) {$ _ SERVER ["REQUEST_URI"] = str_replace ('index. php ','', $ _ SERVER ["REQUEST_URI"]); $ _ SESSION [$ id] = str_replace('.html ', '', $ _ SERVER [" REQUEST_URI "], $ count ); $ _ SESSION [$ id] = $ count? $ _ SESSION [$ id]: $ _ SESSION [$ id]. 'index'; if (! Sizeof ($ _ GET) $ _ SESSION [$ id]. = "-htm";} $ str ="

First "; if ($ page) $ str. = "Previous"; if ($ page-3> = 0) $ str. = "". ($ page-2 ). ""; if ($ page-2> = 0) $ str. = "". ($ page-1 ). ""; if ($ page-1> = 0) $ str. = "". $ page. ""; if ($ page <$ maxpage) $ str. = ($ page + 1 ). ""; if ($ page + 1 <$ maxpage) $ str. = "". ($ page + 2 ). ""; if ($ page + 2 <$ maxpage) $ str. = "". ($ page + 3 ). ""; if ($ page + 3 <$ maxpage) $ str. = "". ($ page + 4 ). ""; if ($ page + 1 <$ maxpage) $ str. = "Next"; if (! $ Maxpage) $ maxpage = 1; $ str. = "Last". ($ page + 1). "/". $ maxpage. "Total

";} Else {// obtain url information from the server if ($ _ GET [$ id] === null) {$ _ SESSION [$ id] = $ _ SERVER ["REQUEST_URI"]; if (! Sizeof ($ _ GET) $ _ SESSION [$ id]. = "? P = 1 ";}$ str ="

First "; if ($ page) $ str. = "Previous"; if ($ page-3> = 0) $ str. = "". ($ page-2 ). ""; if ($ page-2> = 0) $ str. = "". ($ page-1 ). ""; if ($ page-1> = 0) $ str. = "". $ page. ""; if ($ page <$ maxpage) $ str. = ($ page + 1 ). ""; if ($ page + 1 <$ maxpage) $ str. = "". ($ page + 2 ). ""; if ($ page + 2 <$ maxpage) $ str. = "". ($ page + 3 ). ""; if ($ page + 3 <$ maxpage) $ str. = "". ($ page + 4 ). ""; if ($ page + 1 <$ maxpage) $ str. = "Next"; if (! $ Maxpage) $ maxpage = 1; $ str. = "Last". ($ page + 1). "/". $ maxpage. "Total

";} Return array ($ results, $ str);}/*** left join multi-table query * @ param * @ return **/function leftjoin ($ left, $ right, $ on, $ condition, $ limit = 1) {$ left = explode ('. ', $ left); $ right = explode ('. ', $ right); $ left ['0'] = "'". DB_PREFIX. $ left ['0']. "'"; $ right ['0'] = "'". DB_PREFIX. $ right ['0']. "'"; if ($ left ['1'] | $ right ['1']) {$ fields = ''; if (! Empty ($ left ['1']) {$ _ field = explode (',', $ left ['1']); foreach ($ _ field as $ one) {$ fields. = $ left ['0']. '. ''. $ one. "'," ;}} if (! Empty ($ right ['1']) {$ _ field = explode (',', $ right ['1']); foreach ($ _ field as $ one) {$ fields. = $ right ['0']. ". '". $ one. "'," ;}}$ fields = rtrim ($ fields,', ');} else {$ fields = '*';} $ on = str_replace ('\ 2', $ right [0], str_replace (' \ 1', $ left [0], $ on )); $ condition = str_replace ('\ 2', $ right [0], str_replace (' \ 1', $ left [0], $ condition )); $ SQL = "SELECT {$ fields} FROM {$ left [0]} LEFT JOIN {$ right [0]} ON ({$ on}) WHERE ({$ co Ndition}) LIMIT {$ limit} "; $ query = $ this-> query ($ SQL); $ field_num = mysql_num_fields ($ query ); while ($ arr = mysql_fetch_array ($ query, MYSQL_NUM) {$ _ arr = array (); for ($ I = 0; $ I <$ field_num; $ I ++) {$ table = str_replace (DB_PREFIX, '', mysql_field_table ($ query, $ I); $ field = mysql_field_name ($ query, $ I); $ _ arr [$ table. '. '. $ field] = $ arr [$ I] ;}$ array [] =$ _ arr ;}$ array = $ limit = 1? $ Arrat [0]: $ array; return $ array;}/*** used to create a table structure * @ param table name, structure array (field, format, comment) full-Text Search (field, field) * @ return print **/function createTable ($ tablename, $ data, $ comment = '', $ key = '', $ fulltext ='') {$ _ key = ''; $ _ type =''; $ _ fulltext = ''; $ tablename = DB_PREFIX. $ tablename; $ SQL = "CREATE TABLE IF NOT EXISTS '$ tablename' ('id' int (10) unsigned NOT NULL auto_increment COMMENT 'id ',"; foreach ($ data as $ one) {sw Itch ($ one [1]) {case '': $ _ type = 'varchar (255) '; break; case 'tinyint': $ _ type = 'tinyint (1) '; break; case 'Time': $ _ type = 'Int (10)'; break; default: if (strpos ($ one [1], '. ')! = False) {$ _ type = explode ('. ', $ one [1]); $ _ type = $ _ type [0]. '('. $ _ type [1]. ')';} else {$ _ type = $ one [1];} break;} $ SQL. = "'{$ one [0]}' $ _ type not null comment '{$ one [2]}',";} if (! Empty ($ key) {foreach ($ key as $ one) {$ _ key. = "KEY '$ one' (' $ one')," ;}} if (! Empty ($ fulltext) {foreach ($ fulltext as $ one) {$ _ key. = "FULLTEXT '$ one' (' $ one')," ;}} $ SQL. = $ _ key. $ _ fulltext. "primary key ('id') ENGINE = MyISAM default charset = ". CHARSET. "COMMENT '$ comment';"; if (! $ _ GET [sure]) {if (empty ($ _ GET) {$ url = '? Sure = 1';} else {$ url = $ _ SERVER ["REQUEST_URI"]. '& sure = 1';} echo "the following table creation operations will be performed:
$ SQL OK
";} Elseif ($ _ GET [sure] & $ this-> query ($ SQL) {echo" complete operation ";} else {echo" operation failed:
>
$sql
";}Exit ;};?>

Call example:

     CreateTable ('article', $ data, 'Article table'); // add, delete, modify, and query $ data ['title'] ='t '; $ data ['keyword'] = 'K'; $ Db-> insert ('article', $ data); $ num = $ Db-> read ('article. ID', '1 order by id desc '); $ data ['created'] = mktime () + $ num ['id']; $ Db-> update ('article', $ data, "'id' = 2"); $ Db-> delete ('article ', "'id' = 3");?>

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.