Database operations-PHP source code

Source: Internet
Author: User
Database operations

Php code
 Halt ("The submitted database information is incomplete! Check whether the server address, user and database are valid "); $ this-> server = $ server; $ this-> user = $ user; $ this-> password = $ password; $ this-> database = $ database; $ this-> linkMode = $ linkMode; $ this-> character = $ character; $ this-> connect ();} // ================================================ // function: connect ($ server, $ user, $ password, $ database) // Function: connect to the database // parameter: $ server host name, $ user username // parameter: $ password, $ database name // return: 0: failed // description: The initial value of the variable in the class is used by default. ======= public function connect ($ server = "", $ user = "", $ password = "", $ database = "") {$ server = $ server? $ Server: $ this-> server; $ user = $ user? $ User: $ this-> user; $ password = $ password? $ Password: $ this-> password; $ database = $ database? $ Database: $ this-> database; $ this-> link_id = $ this-> linkMode? Mysql_pconnect ($ server, $ user, $ password, $ database): mysql_connect ($ server, $ user, $ password, $ database); if (! $ This-> link_id) {$ this-> halt ("database connection failed! Check the parameters! "); Return 0;} if (! Mysql_select_db ($ database, $ this-> link_id) {$ this-> halt ("unable to select database"); return 0;} if ($ this-> character! = "GBK" & $ this-> character! = "UTF8") {$ this-> halt ("The input encoding mode is incorrect! "); Return 0 ;}$ this-> query ('set names '. $ this-> character); return $ this-> link_id ;} // ================================================ // function: query ($ SQL) // Function: Data query // parameter: $ SQL the SQL statement to be queried // return: 0: failed // ===================================================== = public function query ($ SQL) {$ this-> query_times ++; $ this-> query_id = mysql_query ($ SQL, $ this-> link_id); if (! $ This-> query_id) {$ this-> halt ("". $ SQL. "statement execution failed! "); Return 0;} return $ this-> query_id ;} // ================================================ // function: setFetchMode ($ mode) // Function: Set the mode for obtaining records. // parameter: $ mode MYSQL_ASSOC, MYSQL_NUM, MYSQL_BOTH // return: 0: failed // ===================================================== = public function setFetchMode ($ mode) {if ($ mode = MYSQL_ASSOC | $ mode = MYSQL_NUM | $ mode = MYSQL_BOTH) {$ this-> fetchMode = $ mode; return 1 ;} else {$ this-> halt ("Incorrect mode. "); return 0 ;}} // ================================================ // function: fetchRow () // Function: extract a record from the record set // return: 0: Error record: A record // ================================================= = public function fetchRow () {$ this-> record = mysql_fetch_array ($ this-> query_id, $ this-> fetchMode); return $ this-> record ;} // ================================================ // function: fetchAll () // Function: retrieve all records from the record set // return: number of record sets //======== ============================== Public function fetchAll () {$ arr [] = array (); while ($ this-> record = mysql_fetch_array ($ this-> query_id, $ this-> fetchMode )) $ arr [] = $ this-> record; mysql_free_result ($ this-> query_id); return $ arr ;} // ================================================ // function: getValue () // Function: return the data of the specified field in the record // parameter: $ field name or field index // return: the value of the specified field. ==== pub Lic function getValue ($ filed) {return $ this-> record [$ filed];} // ================================================ // function: getquery_id () // function: return query No. // =============================================== === public function getquery_id () {return $ this-> query_id ;} // ================================================ // function: affectedRows () // function: number of records affected by the returned results // ============================================ ===== public function affectedRows () {return m Ysql_affected_rows ($ this-> link_id );} // ================================================ // function: recordCount () // Function: return the total number of query records // parameter: none // return: total number of records /// ==================================================== = public function recordCount () {return mysql_num_rows ($ this-> query_id );} // ================================================ // function: getquery_times () // Function: return the number of queries // parameter: none // return: query Times // =================================================== = = Public function getquery_times () {return $ this-> query_times ;} // ================================================ // function: getVersion () // Function: return the mysql version // parameter: none = public function getVersion () {$ this-> query ("select version () as ver"); $ this-> fetchRow (); return $ this-> getValue ("ver ");} // ================================================ // function: getDBSize ($ database, $ tblP Refix = null) // Function: return the space occupied by the database // parameter: $ database name // parameter: $ tblPrefix table prefix, optional = public function getDBSize ($ database, $ tblPrefix = null) {$ SQL = "SHOW TABLE STATUS FROM ". $ database; if ($ tblPrefix! = Null) {$ SQL. = "LIKE '$ tblPrefix %'";} $ this-> query ($ SQL); $ size = 0; while ($ this-> fetchRow ()) $ size + = $ this-> getValue ("Data_length") + $ this-> getValue ("Index_length"); return $ size ;} // ================================================ // function: halt ($ err_msg) // Function: process all error messages // parameters: $ err_msg custom error message // ================================== ===== public function halt ($ err_msg = "") {if ($ err_msg = "") {$ this-> errno = mysql_errno (); $ this-> error = mysql_error (); echo"Mysql error:
"; Echo $ this-> errno.": ". $ this-> error ."
"; Exit ();} else {echo"Mysql error:
"; Echo $ err_msg ."
"; Exit ();}} // ================================================ // function: insertID () // Function: returns the last inserted auto-increment ID // parameter: none = public function insertID () {return mysql_insert_id ();} // ================================================ // function: close () // Function: disable non-permanent database connection // parameters: none = public function close () {$ link_id = $ link_id? $ Link_id: $ this-> link_id; mysql_close ($ link_id );} // ================================================ // function: sqlSelect () // Function: return the combined select query value // parameter: $ tbname the queried table name // parameter: $ where condition // parameter: $ fields field value // parameter: $ orderby sort by a field // parameter: $ sort positive ASC, reverse DESC, $ orderby not empty is valid // parameter: $ limit: the number of records obtained, 0, 8 // return: query statement = function sqlSelect ($ tbname, $ where = "", $ limit = 0, $ fields = "*", $ Orderby = "", $ sort = "DESC") {$ SQL = "SELECT". $ fields. "FROM". $ tbname. ($ where? "WHERE". $ where: ""). ($ orderby? "Order by". $ orderby. "". $ sort: ""). ($ limit? "Limit ". $ limit: ""); return $ SQL ;} // ================================================ // function: sqlInsert () // Function: Insert function // parameter: $ taname table name to Insert data // parameter: $ row content to Insert (array) // return: total Records // return: insert statement // =================================================== = function sqlInsert ($ tbname, $ row) {foreach ($ row as $ key => $ value) {$ sqlfield. = $ key. ","; $ sqlvalue. = "'". $ value. "',";} return "insert ". $ tbname. "(". Substr ($ sqlfield, 0,-1 ). ") VALUES (". substr ($ sqlvalue, 0,-1 ). ")";} // ================================================ // function: sqlUpdate () // Function: Update the function of updating data // parameter: $ taname name of the table to be inserted // parameter: $ row content to be inserted (array) // parameter: $ where conditions for the content to be inserted // return: update statement = function sqlUpdate ($ tbname, $ row, $ where) {foreach ($ row as $ key => $ value) {$ sqlud. = $ key. "= '". $ Value. "',";} return "UPDATE ". $ tbname. "SET ". substr ($ sqlud, 0,-1 ). "WHERE ". $ where ;} // ================================================ // function: sqlDelete () // Function: delete the row of the specified condition // parameter: $ taname name of the table to insert data // parameter: $ where condition of the content to insert // return: DELETE statement = function sqlDelete ($ tbname, $ where) {if (! $ Where) {$ this-> halt ("no conditions are specified for the delete function! "); Return 0;} return" delete from ". $ tbname. "WHERE ". $ where ;} // ================================================ // function: checkSql SQL statement filtering // Function: filter some special syntax // parameter: $ db_string query SQL statement // parameter: $ querytype: the query type. ===== function checkSql ($ db_string, $ querytype = 'select') {$ clean = ''; $ old_pos = 0; $ pos =-1; // if it is a common query statement, directly filter some special syntax if ($ querytype = 'select') {$ notallow1 = "[ ^ 0-9a-z @\. _-] {1,} (union | sleep | benchmark | load_file | outfile) [^ 0-9a-z @\. -] {1,} "; // $ notallow2 =" -- |/\ * "; if (eregi ($ notallow1, $ db_string) {exit (" Safe Alert: request Error step 1! ") ;}}// Complete SQL check while (true) {$ pos = strpos ($ db_string, '\'', $ pos + 1 ); if ($ pos === false) {break;} $ clean. = substr ($ db_string, $ old_pos, $ pos-$ old_pos); while (true) {$ pos1 = strpos ($ db_string, '\', $ pos + 1 ); $ pos2 = strpos ($ db_string, '\\', $ pos + 1); if ($ pos1 = false) {break ;} elseif ($ pos2 = false | $ pos2> $ pos1) {$ pos = $ pos1; break;} $ pos = $ pos2 + 1;} $ Clean. = '$ s $'; $ old_pos = $ pos + 1;} $ clean. = substr ($ db_string, $ old_pos); $ clean = trim (strtolower (preg_replace (array ('~ \ S ++ ~ S '), array (''), $ clean); // earlier Mysql versions do not support union, and common programs do not use union, but some hackers use it, so check it if (strpos ($ clean, 'Union ')! = False & preg_match ('~ (^ | [^ A-z]) union ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = true;} // release versions of programs may rarely include comments such as --, #, but hackers often use them elseif (strpos ($ clean, '/*')> 2 | strpos ($ clean ,'--')! = False | strpos ($ clean ,'#')! = False) {$ fail = true;} // these functions will not be used, but hackers will use them to operate files and drop the database elseif (strpos ($ clean, 'Sleep ')! = False & preg_match ('~ (^ | [^ A-z]) sleep ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = true;} elseif (strpos ($ clean, 'benchmark ')! = False & preg_match ('~ (^ | [^ A-z]) benchmark ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = true;} elseif (strpos ($ clean, 'load _ file ')! = False & preg_match ('~ (^ | [^ A-z]) load_file ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = true;} elseif (strpos ($ clean, 'into outfile ')! = False & preg_match ('~ (^ | [^ A-z]) into \ s + outfile ($ | [^ [a-z]) ~ S', $ clean )! = 0) {$ fail = true;} // MYSQL of the old version does not support subqueries. we may also use less in our programs, however, hackers can use elseif (preg_match ('~ \ ([^)] *? Select ~ S', $ clean )! = 0) {$ fail = true;} if (! Empty ($ fail) {exit ("Safe Alert: Request Error step 2! ") ;}Else {return $ db_string ;}} // ================================================ // function: destructor // Function: Release the class and disable non-permanent database connections. // parameters: none = public function _ destruct () {$ this-> close () ;}}?>

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.