The following code is rewritten using a previous class named MyPDO. The Singleton mode is introduced to ensure that the class is not repeatedly instantiated in global calls, reducing the waste of system resources, most php operations are related to various databases, including mysql, redis, and m... the following code is rewritten using a previous class named MyPDO. The Singleton mode is introduced to ensure that the class is not repeatedly instantiated in global calls, reducing the waste of system resources, most php operations are related to various databases, including mysql, redis, memcache, and other relational and non-relational databases. Therefore, a large number of database connection operations exist in an application, if the Singleton mode is not used, the new operation is required each time, but the new operation consumes a lot of memory resources and system resources, each time you open or close a database connection, it is a great test and waste for the database. the code is as follows:
Dsn = 'MySQL: host = '. $ dbHost. '; dbname = '. $ dbName; $ this-> dbh = new PDO ($ this-> dsn, $ dbUser, $ dbPasswd); $ this-> dbh-> exec ('set character_set_connection = '. $ dbCharset. ', character_set_results = '. $ dbCharset. ', character_set_client = binary');} catch (PDOException $ e) {$ this-> outputError ($ e-> getMessage ());}} /***** prevent cloning **/private function _ clone () {}/***** Singleton instance ** @ return Object */public static function getInstance ($ dbHost, $ dbUser, $ dbPasswd, $ dbName, $ dbCharset) {if (self ::$ _ instance === null) {self:: $ _ instance = new self ($ dbHost, $ dbUser, $ dbPasswd, $ dbName, $ dbCharset);} return self ::$ _ instance ;} /*** Query ** @ param String $ strSql SQL statement * @ param String $ queryMode Query method (All or Row) * @ param Boolean $ debug * @ return Array */public function query ($ strSq L, $ queryMode = 'all', $ debug = false) {if ($ debug = true) $ this-> debug ($ strSql ); $ recordset = $ this-> dbh-> query ($ strSql); $ this-> getPDOError (); if ($ recordset) {$ recordset-> setFetchMode (PDO :: FETCH_ASSOC); if ($ queryMode = 'all') {$ result = $ recordset-> fetchAll ();} elseif ($ queryMode = 'row ') {$ result = $ recordset-> fetch () ;}} else {$ result = null;} return $ result ;}/ *** Update * * @ Param String $ table name * @ param Array $ arrayDataValue field and value * @ param String $ where condition * @ param Boolean $ debug * @ return Int */public function update ($ table, $ arrayDataValue, $ where = '', $ debug = false) {$ this-> checkFields ($ table, $ arrayDataValue); if ($ where) {$ strSql = ''; foreach ($ arrayDataValue as $ key => $ value) {$ strSql. = ", '$ key' =' $ value'";} $ strSql = substr ($ strSql, 1); $ strSql = "Updat' $ table 'set $ strSql WHERE $ where";} else {$ strSql = "replace into '$ table '("'. implode ('','', array_keys ($ arrayDataValue )). "') VALUES ('". implode ("','", $ arrayDataValue ). "')";} if ($ debug = true) $ this-> debug ($ strSql ); $ result = $ this-> dbh-> exec ($ strSql); $ this-> getPDOError (); return $ result ;} /*** Insert ** @ param String $ table name * @ param Array $ arrayDataValue field and value * @ Param Boolean $ debug * @ return Int */public function insert ($ table, $ arrayDataValue, $ debug = false) {$ this-> checkFields ($ table, $ arrayDataValue ); $ strSql = "insert into '$ table '("'. implode ('','', array_keys ($ arrayDataValue )). "') VALUES ('". implode ("','", $ arrayDataValue ). "')"; if ($ debug = true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql ); $ this-> getPDOError (); return $ Result ;} /*** insert in Replace mode ** @ param String $ table name * @ param Array $ arrayDataValue field and value * @ param Boolean $ debug * @ return Int */public function replace ($ table, $ arrayDataValue, $ debug = false) {$ this-> checkFields ($ table, $ arrayDataValue); $ strSql = "replace into '$ table '("'. implode ('','', array_keys ($ arrayDataValue )). "') VALUES ('". implode ("','", $ arrayDataValue ). "')"; if ($ debu G === true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql); $ this-> getPDOError (); return $ result ;} /*** Delete delete ** @ param String $ table name * @ param String $ where condition * @ param Boolean $ debug * @ return Int */public function Delete ($ table, $ where = '', $ debug = false) {if ($ where ='') {$ this-> outputError ("'Where' is Null ");} else {$ strSql = "delete from '$ table' WHERE $ where "; If ($ debug = true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql ); $ this-> getPDOError (); return $ result ;}} /*** execSql execute SQL statement ** @ param String $ strSql * @ param Boolean $ debug * @ return Int */public function execSql ($ strSql, $ debug = false) {if ($ debug = true) $ this-> debug ($ strSql); $ result = $ this-> dbh-> exec ($ strSql ); $ this-> getPDOError (); return $ result;}/*** obtain the maximum value of a field * * @ Param string $ table name * @ param string $ field_name field name * @ param string $ where condition */public function getMaxValue ($ table, $ field_name, $ where = '', $ debug = false) {$ strSql = "select max (". $ field_name. ") AS MAX_VALUE FROM $ table"; if ($ where! = '') $ StrSql. = "WHERE $ where"; if ($ debug = true) $ this-> debug ($ strSql); $ arrTemp = $ this-> query ($ strSql, 'row'); $ maxValue = $ arrTemp ["MAX_VALUE"]; if ($ maxValue = "" | $ maxValue = null) {$ maxValue = 0 ;} return $ maxValue ;} /*** get the number of specified columns ** @ param string $ table * @ param string $ field_name * @ param string $ where * @ param bool $ debug * @ return int */ public function getCount ($ table, $ fiel D_name, $ where = '', $ debug = false) {$ strSql =" select count ($ field_name) as num from $ table "; if ($ where! = '') $ StrSql. = "WHERE $ where"; if ($ debug = true) $ this-> debug ($ strSql); $ arrTemp = $ this-> query ($ strSql, 'row'); return $ arrTemp ['num'];} /*** get table engine ** @ param String $ dbName database name * @ param String $ tableName table name * @ param Boolean $ debug * @ return String */public function getTableEngine ($ dbName, $ tableName) {$ strSql = "show table status from $ dbName WHERE Name = '". $ tableName. "'"; $ arrayTableI Nfo = $ this-> query ($ strSql); $ this-> getPDOError (); return $ arrayTableInfo [0] ['engine'];} /*** intransaction transaction start */private function beginTransaction () {$ this-> dbh-> beginTransaction ();} /*** commit transaction commit */private function commit () {$ this-> dbh-> commit ();} /*** rollback transaction rollback */private function rollback () {$ this-> dbh-> rollback ();} /*** transaction: process multiple SQL statements through transactions. * getTableEngine must be used to determine whether a transaction is called. Whether the table breaking engine supports transactions ** @ param array $ arraySql * @ return Boolean */public function execTransaction ($ arraySql) {$ retval = 1; $ this-> beginTransaction (); foreach ($ arraySql as $ strSql) {if ($ this-> execSql ($ strSql) = 0) $ retval = 0;} if ($ retval = 0) {$ this-> rollback (); return false;} else {$ this-> commit (); return true ;}} /*** checkFields: Check whether the specified field exists in the specified data table ** @ param String $ table * @ param array $ RrayField */private function checkFields ($ table, $ arrayFields) {$ fields = $ this-> getFields ($ table); foreach ($ arrayFields as $ key => $ value) {if (! In_array ($ key, $ fields) {$ this-> outputError ("Unknown column '$ key' in field list. ") ;}}/ *** getFields: Get all field names in the specified data table ** @ param String $ table name * @ return array */private function getFields ($ table) {$ fields = array (); $ recordset = $ this-> dbh-> query ("show columns from $ table"); $ this-> getPDOError (); $ recordset-> setFetchMode (PDO: FETCH_ASSOC); $ result = $ recordset-> fetchAll (); foreach ($ resu Lt as $ rows) {$ fields [] = $ rows ['field'];} return $ fields ;} /*** getPDOError capture PDO error information */private function getPDOError () {if ($ this-> dbh-> errorCode ()! = '000000') {$ arrayError = $ this-> dbh-> errorInfo (); $ this-> outputError ($ arrayError [2]);} /*** debug ** @ param mixed $ debuginfo */private function debug ($ debuginfo) {var_dump ($ debuginfo); exit ();} /*** output Error message ** @ param String $ strErrMsg */private function outputError ($ strErrMsg) {throw new Exception ('MySQL Error :'. $ strErrMsg);}/*** destruct close database connection */public function destruct () {$ this-> dbh = null ;}}
Call method:
destruct();
Article URL:
Reprint ^ at will, but please attach the tutorial address.