Mysql operation library 1.2

Source: Internet
Author: User
After a small change, the latest version is released :? Php ** + ---------------------------------- * MySQL operation class library + ------------------------------------ * @ author Ma Yun + ---------------------------------- * @ version1.2 (2013-5-31) + -----------------------

After a small change, the latest version is released :? Php/** + ---------------------------------- * MySQL operation class library + ------------------------------------ * @ author Ma Yun + Yun * @ version 1.2 () + -----------------------

After a small change, the latest version is released:

 DbName = $ DBName; $ this-> connect ();}/** + ------------------------------------------------------------ * connection method + login * @ access public + login */public function connect () {if ($ this-> linkID = 0) {$ this-> linkID = mysql_connect ($ this-> Host, $ this-> UserName, $ this-> Password, true, CLIENT_MULTI _ RESULTS); if (! $ This-> linkID) {$ this-> errorMsg = 'database connection error \ r \ n'. mysql_error (); $ this-> halt () ;}} if (! Mysql_select_db ($ this-> dbName, $ this-> linkID) {$ this-> errorMsg = 'failed to open the database '. mysql_error ($ this-> linkID); $ this-> halt ('failed to open the database ');} $ dbVersion = mysql_get_server_info ($ this-> linkID ); if ($ dbVersion> = "4.1") {// mysql 4.1.0 or above is required to use UTF8 to access the database. mysql supports mysql_query ("set names '". $ this-> dbCharSet. "'", $ this-> linkID);} // sets CharSet mysql_query ('set character set \''. $ this-> dbCharSet. '\ '', $ this-> linkID); // Set SQL _model if ($ dbVersion> '5. 0.1 ') {mysql_query ("SET SQL _mode ='' ", $ this-> linkID );}} /** + release * release query result + response * @ access public + ------------------------------------------------------------ */public function free () {if ($ this-> queryID! = Null) mysql_free_result ($ this-> queryID); $ this-> queryID = null ;} /** + statement * execution statement + response * @ access public + ------------------------------------------------------------ * @ param string $ SQL command + response * @ return bool or resource + ---------- -------------------------------------------- */Public function execute ($ SQL) {if ($ this-> linkID = 0) $ this-> connect (); $ this-> lastSql = $ SQL; $ this-> queryID = mysql_query ($ SQL); if (false = $ this-> queryID) {$ this-> errorMsg = 'SQL statement execution failed \ r \ n '. mysql_error ($ this-> linkID); return false;} else {return $ this-> queryID;}/** + ---------------------------------------------------------- * Get Record The number of rows in the Set + response * @ access public + -------------------------------------------------- * @ param string $ SQL command can be blank * if it is blank: return the number of records in the previous result set * if not empty: returns the number of records of the current SQL statement + response * @ return integer + ------------------------------------------------------ */public function getRowsNum ($ SQL = '') {if ($ thi S-> linkID = 0) {$ this-> connect () ;}if ($ SQL! = '') {$ This-> execute ($ SQL);} return mysql_num_rows ($ this-> queryID );} /** + ignore * form data is directly inserted into the data table + ---------------------------------------------------------- * @ access public + reply * @ param string $ tableName data table name + response * @ return success Failed to return false + response */public function form2db ($ tableName) {$ _ POST ["add_time"] = date ('Y-m-d H: i: s'); $ data =$ _ POST; $ this-> fields = $ this-> getFields ($ tableName ); $ data = $ this-> _ facade ($ data); if ($ this-> insert ($ tableName, $ data) {return $ this-> lastInsID ;} else {return false ;}/ ** + --------------------------------------------------- ------- * Insert data directly into the data table + export * @ access public + export * @ param string $ tableName data table name + export * @ param array $ name of the data key inserted by data corresponds to the field name, key Value + ---------------------------------------------------------- * @ return boolean + --------------------------- ----------------------------- */Public function insert ($ tableName, $ data) {$ values = $ fields = array (); foreach ($ data as $ key => $ val) {$ value = '\''. addslashes ($ val ). '\ '''; if (is_scalar ($ value) {// filter non-standard data $ values [] = $ value; $ fields [] = $ key ;}} $ SQL = 'insert '. trim ($ tableName ). '('. implode (',', $ fields ). ') VALUES ('. implode (',', $ values ). ')'; if ($ this-> execute ($ SQL) {$ This-> errorMsg = 'insertion failed \ r \ n '. mysql_error ($ this-> linkID); $ this-> lastInsID = mysql_insert_id ($ this-> linkID); return true;} else {return false ;}} /** + ---------------------------------------------------------- * update operation + ---------------------------------------------------------- * @ access public + signature * @ param string $ tableName data table name + ---- ---------------------------------------------------- * @ Param array $ the data key inserted by data corresponds to the field name, the key value corresponds to the value + condition * @ param array $ condition update condition. For security reasons, cannot be blank + -------------------------------------------------------- * @ param array $ isForm can be empty. The default value is true * if it is true, it will be processed as a form update table. The field is automatically mapped * If, it will be processed as a normal update and will not automatically map fields + ----------------------------------------- ----------------- * @ Return boolean + condition */public function update ($ tableName, $ data, $ condition, $ isForm = true) {if (empty ($ condition )) {$ this-> errorMsg = 'Update condition not set '; return false;} // process decomposition conditionif (is_array ($ condition) {$ condition = self :: _ parseCondition ($ condition);} if ($ isForm) {$ this-> fields = $ this-> getFields ($ tableName); $ data = $ t His-> _ facade ($ data);} $ SQL = 'update '. trim ($ tableName ). 'set'; foreach ($ data as $ key => $ val) {$ SQL. = $ key. '= \''. $ val. '\', ';} $ SQL = substr ($ SQL, 0, strlen ($ SQL)-1); $ SQL. = 'where '. $ condition; if ($ this-> execute ($ SQL) {return true;} else {$ this-> errorMsg = 'Update failed \ r \ n '. mysql_error ($ this-> linkID); return false ;}/ ** + --------------------------------------------------- ------- * Delete operation + condition * @ access public + -------------------------------------------------------- * @ param string $ tableName data table name + condition * @ param array $ condition update condition, for security reasons, cannot be blank + ---------------------------------------------------------- * @ return boolean + ----------------------------------- ----------------------- */Public function delete ($ tableName, $ condition) {// process decomposition conditionif (is_array ($ condition) {$ condition = self :: _ parseCondition ($ condition);} $ SQL = 'delete from '. $ tableName. 'Where 1 = 1 and '. $ condition; if (! $ This-> execute ($ SQL) return false; return true ;} /** + ---------------------------------------------------------- * use the _ call magic method to implement some special Model methods + using * @ access public + using * @ param string $ method name * @ param array $ args call parameters + ---------------------------------------------------------- * @ re Turn mixed + combine */public function _ call ($ method, $ args) {/* obtain the value of the record field based on a field * Example 1: getFieldByid (student_info, 100, name) --- get the name of the student whose id is 100 in the student table * Example 2: getFieldByxh (student_info, 201215030223, address) --- get the address of the student table No. 201015030223 * Note: "getFieldBy" is case insensitive. The field names are case sensitive. * return value: string */if (strtolower (substr ($ method,) = 'getfieldby ') {$ name = substr ($ method, 1 0); $ SQL = 'select ''. $ args [2]. ''from '. $ args [0]. 'where '. $ name. '= \''. $ args [1]. '\ ''; if ($ this-> execute ($ SQL) {$ row = mysql_fetch_array ($ this-> queryID); return $ row [0];} else {return false;}/* obtain a record based on a field and value * Example 1: getByid (student_info, 100) --- obtain the student information with the id of 100 in the student table * Example 2: getByxh (student_info, 201215030223) --- obtain the student information with the id of 201015030223 in the student table * Note: "getBy" is case insensitive, the subsequent field names are case sensitive * return value: array */elseif (strtolower (substr ($ m Ethod, 0, 5) = 'getby') {$ ret = array (); $ name = substr ($ method, 5); $ SQL = 'select * from '. $ args [0]. 'where '. $ name. '= \''. $ args [1]. '\ ''; if ($ this-> execute ($ SQL) {$ row = mysql_fetch_array ($ this-> queryID); return $ row ;} else {return false ;}}/ ** + -------------------------------------------------------------- the error message is displayed, and the running is terminated + running * @ access public + ------- ------------------------------------------------- * @ Param string $ msg error message, can be empty + response */public static function halt ($ msg = '') {if ($ msg! = '') {$ Msg. = '\ r \ n';} $ error = mysql_error (); die ($ msg );} /** + response * Get the last query ID + ---------------------------------------------------------- * @ access public + response */public function getQueryId () {return $ this-> queryID ;} /** + ------------------------------------------------------------ * Take the last database operation error message + response * @ access public + ---------------------------------------------------------- */public function getLastError () {return $ this-> errorMsg ;} /** + explain * obtain the last executed SQL statement + -------------------------------------------------------------- * @ access public + --------------------------- ----------------------------- */Public function getLastSql () {return $ this-> lastSql ;} /** + comment * Get the index ID number of the last inserted database record + comment * @ access public + comment */public function getLastInsID () {return $ this-> lastInsID ;} /** + ------------------ -------------------------------------- * Obtain the number of rows affected by the previous operation + response * @ access public + response */public function getAffectedRows () {return mysql_affected_rows ($ this-> linkID );} /** + ---------------------------------------------------------- * obtain the field information of the data table + --------------------------------------------- ------------- * @ Access public + functions */public function getFields ($ tableName) {$ result = array (); $ this-> execute ('show columns from '. $ this-> parseKey ($ tableName); while ($ row = mysql_fetch_array ($ this-> queryID) {$ result [] = $ row ;} $ info = array (); if ($ result) {foreach ($ result as $ key => $ val) {$ info [$ val ['field'] = array ('name' => $ Val ['field'], 'type' => $ val ['type'], 'notnull '=> (bool) ($ val ['null'] = ''), // not Null is empty, null is yes 'default' => $ val ['default'], 'primary' => (strtolower ($ val ['key']) = 'pri '), 'autoinc' => (strtolower ($ val ['extra']) = 'auto_increment '),) ;}return $ info;}/** + add field and table name processing' + ------------------------------------------ ---------------- * @ Access protected + principal * @ param string $ key + -------------------------------------------------------- * @ return string + principal */protected function parseKey (& $ key) {$ key = trim ($ key); if (false! = Strpos ($ key, '') | false! = Strpos ($ key, ',') | false! = Strpos ($ key, '*') | false! = Strpos ($ key, '(') | false! = Strpos ($ key, '.') | false! = Strpos ($ key, ''') {// If * is included or the SQL method is used, no processing is performed.} else {$ key = '''. $ key. ''';} return $ key ;} /** + Processing * process the data stored in the database + Processing * @ access protected + Processing * @ param mixed $ data the data to be operated + -------------------------------------------------- -------- * @ Return boolean + -------------------------------------------------------- */private function _ facade ($ data) {// check non-data field if (! Empty ($ this-> fields) {foreach ($ data as $ key => $ val) {if (! Array_key_exists ($ key, $ this-> fields) {unset ($ data [$ key]) ;}}return $ data;} public function close () {mysql_close ($ this-> linkID);} public function _ destruct () {$ this-> close ();} /*** 2013.5.25 add */public function getPk ($ table) {// set pk to null $ this-> pk = null; $ result = $ this-> getFields ($ table); foreach ($ result as $ key => $ val) {if ($ val ['primary']) {$ this-> pk = $ key; break;} return $ this-> pk;} public function Fetch (& $ rst = null, $ array_type = MYSQL_ASSOC) {if ($ rst = null) {$ rst = $ this-> queryID ;} if ($ this-> queryID) return mysql_fetch_array ($ rst, $ array_type); elsereturn false;} // decomposition condition private function _ parseCondition ($ condition, $ operator = 'and') {$ return = ''; if (is_array ($ condition) {$ index = 0; foreach ($ condition as $ key => $ value) {if ($ index) {$ return. = "". $ operator;} $ return. = "'{$ key}' = '{$ Value}' "; $ index ++;} return $ return;} else {return false ;}/ * Start Transaction Processing */public function beginTransaction () {$ this-> execute ("start transaction");} public function commit () {$ this-> execute ("COMMIT");} public function rollback () {$ this-> execute ("ROLLBACK");}/* transaction processing ends * // search for a public function find ($ table, $ condition = null, $ field = null) {if (is_array ($ condition) {$ condition = self: _ parseCo Ndition ($ condition);} // process condition and field $ condition = null? Null: (is_array ($ condition )? Self: _ parseCondition ($ condition): $ condition); $ field = null? '*': (Is_array ($ field )? Implode (",", $ field): $ field); $ SQL = 'select'. $ field. 'from'. $ table; if ($ condition! = Null) {$ SQL. = "WHERE ". $ condition;} return $ this-> findOneBySql ($ SQL);} // query all records public function findAll ($ table, $ condition = null, $ field = null) {if (is_array ($ condition) {$ condition = self ::_ parseCondition ($ condition) ;}// process condition and field $ condition = null? Null: (is_array ($ condition )? Self: _ parseCondition ($ condition): $ condition); $ field = null? '*': (Is_array ($ field )? Implode (",", $ field): $ field); $ SQL = 'select'. $ field. 'from'. $ table; if ($ condition! = Null) {$ SQL. = "WHERE ". $ condition;} return $ this-> findallBySql ($ SQL);} public function findOneBySql ($ SQL) {$ SQL. = "LIMIT 1"; $ this-> execute ($ SQL); return $ this-> fetch ();} public function findAllBySql ($ SQL) {$ rows = array (); $ this-> execute ($ SQL); while ($ row = $ this-> fetch ()) {$ rows [] = $ row;} return $ rows;} public function findByPk ($ table, $ _ pk) {$ pk = $ this-> getPk ($ table ); if ($ pk = null) {$ this-> errorMsg = "The primary key of the table is not found"; return false;} else {return $ this-> find ($ table, array ($ pk =>$ _ pk ));}} public function deleteByPk ($ table, $ _ pk) {$ pk = $ this-> getPk ($ table); if ($ pk = null) {$ this-> errorMsg = "the primary key of the table is not found"; return false;} else {$ SQL = "DELETE FROM ". $ table. "WHERE '{$ pk}' = '{$ _ pk}'"; return $ this-> delete ($ table, array ($ pk =>$ _ pk ));}}} /** class library update log 2013.5.25*1. The conditions in the update delete operation can be set to the array format $ key => $ value * 2. The transaction processing function is added (only for I Nnodb engine) * 3. Add search for a record by condition * 4. Add search for all records by condition * 5. Add search records by primary key * 6. Add delete records by primary key */?>

Original article address: mysql operation class library 1.2. Thank you for sharing it.

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.