Use the PDO method in php to add, delete, modify, and query databases and use the class Singleton-PHP source code

Source: Internet
Author: User
Use the PDO method in php to add, delete, modify, and query databases and skip to the class Singleton

Class DPDO {private $ DSN; private $ DBUser; private $ DBPwd; private $ longLink; private $ pdo; // private constructor prevents private function _ construct from being directly instantiated ($ dsn, $ DBUser, $ DBPwd, $ longLink = false) {$ this-> DSN = $ dsn; $ this-> DBUser = $ DBUser; $ this-> DBPwd = $ DBPwd; $ this-> longLink = $ longLink; $ this-> connect ();} // private empty clone function prevents private function _ clone () {}// the static instantiation function returns a pdo object static public function instance ($ dsn, $ DBUser, $ DBPwd, $ longLink = false) {static $ singleton = array (); // static functions are used to store instantiated objects $ singIndex = md5 ($ dsn. $ DBUser. $ DBPwd. $ longLink); if (empty ($ singleton [$ singIndex]) {$ singleton [$ singIndex] = new self ($ dsn, $ DBUser, $ DBPwd, $ longLink = false);} return $ singleton [$ singIndex]-> pdo;} private function connect () {try {if ($ this-> longLink) {$ this-> pdo = new PDO ($ this-> DSN, $ this-> DBUser, $ this-> DBPwd, array (PDO :: ATTR_PERSISTENT => true);} else {$ this-> pdo = new PDO ($ this-> DSN, $ this-> DBUser, $ this-> DBPwd );} $ this-> pdo-> query ('set NAMES UTF-8 ');} catch (PDOException $ e) {die ('Error :'. $ e-> getMessage (). '');}}}

2. [Code]It is used to process field ing. using pdo field ING can effectively avoid SQL injection.
// Field Association array processing, mainly used to write and update data, query conditions with the same and or, generate an array of SQL statements and ing fields public function FDFields ($ data, $ link = ',', $ judge = array (), $ aliasTable = '') {$ SQL =''; $ mapData = array (); foreach ($ data as $ key => $ value) {$ mapIndex = ':'. ($ link! = ','? 'C': ''). $ aliasTable. $ key; $ SQL. =''. ($ aliasTable? $ AliasTable. '.': ''). '''. $ key. '''. ($ judge [$ key]? $ Judge [$ key]: '= '). ''. $ mapIndex. ''. $ link; $ mapData [$ mapIndex] = $ value;} $ SQL = trim ($ SQL, $ link); return array ($ SQL, $ mapData );} // process a single field. public function FDField ($ field, $ value, $ judge = ', $ preMap = 'cn', $ aliasTable = '') {$ mapIndex = ':'. $ preMap. $ aliasTable. $ field; $ SQL = ''. ($ aliasTable? $ AliasTable. '. ':''). '''. $ field. '''. $ judge. $ mapIndex; $ mapData [$ mapIndex] = $ value; return array ($ SQL, $ mapData );} // use the preceding method to easily generate query conditions and the corresponding data array public function FDCondition ($ condition, $ mapData) {if (is_string ($ condition )) {$ where = $ condition;} else if (is_array ($ condition) {if ($ condition ['str']) {if (is_string ($ condition ['str']) {$ where = $ condition ['str'];} else {return false ;}} if (is_array ($ Condition ['data']) {$ link = $ condition ['link']? $ Condition ['link']: 'and'; list ($ conSql, $ mapConData) = $ this-> FDFields ($ condition ['data'], $ link, $ condition ['Judge ']); if ($ conSql) {$ where. = ($ where? ''. $ Link:''). $ conSql; $ mapData = array_merge ($ mapData, $ mapConData) ;}} return array ($ where, $ mapData );}

3. [Code]Specific implementation of addition, deletion, modification, and query
public function fetch($sql, $searchData = array(), $dataMode = PDO::FETCH_ASSOC, $preType = array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)) {if ($sql) {$sql .= ' limit 1';$pdoStatement = $this->pdo->prepare($sql, $preType);$pdoStatement->execute($searchData);return $data = $pdoStatement->fetch($dataMode);} else {return false;}}public function fetchAll($sql, $searchData = array(), $limit = array(0, 10), $dataMode = PDO::FETCH_ASSOC, $preType = array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY)) {if ($sql) {$sql .= ' limit ' . (int) $limit[0] . ',' . (intval($limit[1]) > 0 ? intval($limit[1]) : 10);$pdoStatement = $this->pdo->prepare($sql, $preType);$pdoStatement->execute($searchData);return $data = $pdoStatement->fetchAll($dataMode);} else {return false;}}public function insert($tableName, $data, $returnInsertId = false, $replace = false) {if(!empty($tableName) && count($data) > 0){$sql = $replace ? 'REPLACE INTO ' : 'INSERT INTO ';list($setSql, $mapData) = $this->FDFields($data);$sql .= $tableName . ' set ' . $setSql;$pdoStatement = $this->pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));$execRet = $pdoStatement->execute($mapData);return $execRet ? ($returnInsertId ? $this->pdo->lastInsertId() : $execRet) : false;} else {return false;}}public function update($tableName, $data, $condition, $mapData = array(), $returnRowCount = true) {if(!empty($tableName) && count($data) > 0) {$sql = 'UPDATE ' . $tableName . ' SET ';list($setSql, $mapSetData) = $this->FDFields($data);$sql .= $setSql;$mapData = array_merge($mapData, $mapSetData);list($where, $mapData) = $this->FDCondition($condition, $mapData);$sql .= $where ? ' WHERE ' . $where : '';$pdoStatement = $this->pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));$execRet = $pdoStatement->execute($mapData);return $execRet ? ($returnRowCount ? $pdoStatement->rowCount() : $execRet) : false;} else {return false;}}public function delete($tableName, $condition, $mapData = array()) {if(!empty($tableName) && $condition){$sql = 'DELETE FROM ' . $tableName;list($where, $mapData) = $this->FDCondition($condition, $mapData);$sql .= $where ? ' WHERE ' . $where : '';$pdoStatement = $this->pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));$execRet = $pdoStatement->execute($mapData);return $execRet;}}

4. [Code]Test File
Header ("Content-type: text/html; charset = utf-8"); define ('app _ dir', dirname (_ FILE __)); if (function_exists ('SPL _ autoload_register ') {spl_autoload_register ('autoclass');} else {function _ auto_load ($ className) {autoClass ($ className );}} function autoClass ($ className) {try {require_once APP_DIR. '/class /'. $ className. '. php ';} catch (Exception $ e) {die ('Error :'. $ e-> getMessage (). '') ;}}$ DB = new DB (); // Insert $ InData ['A'] = rand (1,100); $ inData ['B'] = rand (1, 1000); $ inData ['c'] = rand (1,200 ). '. '. rand (1,100); $ ret = $ DB-> insert ('A', $ inData); echo 'insert '. ($ ret? 'Success': 'failed'). ''; // update $ upConData ['A'] = 100; $ upConJudge ['A'] ='

5. [File]Test. php ~ 2 KB


6. [File]DB. php ~ 4 KB

DebugDumpParams () can view SQL statement errors */class DB {protected $ pdo; public function _ construct ($ dbType = 'mysql ') {if ($ dbType = 'mysql') {$ dsn = "mysql: host = localhost; port = 3306; dbname = test" ;}$ this-> pdo = DPDO:: instance ($ dsn, 'root', '');} public function fetch ($ SQL, $ searchData = array (), $ dataMode = PDO: FETCH_ASSOC, $ preType = array (PDO: ATTR_CURSOR => PDO: CURSOR_FWDONLY) {if ($ SQL) {$ SQL. = 'limit 1'; $ p DoStatement = $ this-> pdo-> prepare ($ SQL, $ preType); $ pdoStatement-> execute ($ searchData ); return $ data = $ pdoStatement-> fetch ($ dataMode);} else {return false;} public function fetchAll ($ SQL, $ searchData = array (), $ limit = array (0, 10), $ dataMode = PDO: FETCH_ASSOC, $ preType = array (PDO: ATTR_CURSOR => PDO: CURSOR_FWDONLY )) {if ($ SQL) {$ SQL. = 'limit '. (int) $ limit [0]. ','. (intval ($ limit [1])> 0? Intval ($ limit [1]): 10); $ pdoStatement = $ this-> pdo-> prepare ($ SQL, $ preType ); $ pdoStatement-> execute ($ searchData); return $ data = $ pdoStatement-> fetchAll ($ dataMode);} else {return false;} public function insert ($ tableName, $ data, $ returnInsertId = false, $ replace = false) {if (! Empty ($ tableName) & count ($ data)> 0) {$ SQL = $ replace? 'Replace into': 'Insert into'; list ($ setSql, $ mapData) = $ this-> FDFields ($ data); $ SQL. = $ tableName. 'set '. $ setSql; $ pdoStatement = $ this-> pdo-> prepare ($ SQL, array (PDO: ATTR_CURSOR => PDO: CURSOR_FWDONLY )); $ execRet = $ pdoStatement-> execute ($ mapData); return $ execRet? ($ ReturnInsertId? $ This-> pdo-> lastInsertId (): $ execRet): false;} else {return false ;}} public function update ($ tableName, $ data, $ condition, $ mapData = array (), $ returnRowCount = true) {if (! Empty ($ tableName) & count ($ data)> 0) {$ SQL = 'update '. $ tableName. 'set'; list ($ setSql, $ mapSetData) = $ this-> FDFields ($ data); $ SQL. = $ setSql; $ mapData = array_merge ($ mapData, $ mapSetData); list ($ where, $ mapData) = $ this-> FDCondition ($ condition, $ mapData ); $ SQL. = $ where? 'Where '. $ where: ''; $ pdoStatement = $ this-> pdo-> prepare ($ SQL, array (PDO: ATTR_CURSOR => PDO: CURSOR_FWDONLY )); $ execRet = $ pdoStatement-> execute ($ mapData); return $ execRet? ($ ReturnRowCount? $ PdoStatement-> rowCount (): $ execRet): false;} else {return false;} public function delete ($ tableName, $ condition, $ mapData = array ()) {if (! Empty ($ tableName) & $ condition) {$ SQL = 'delete from '. $ tableName; list ($ where, $ mapData) = $ this-> FDCondition ($ condition, $ mapData); $ SQL. = $ where? 'Where '. $ where: ''; $ pdoStatement = $ this-> pdo-> prepare ($ SQL, array (PDO: ATTR_CURSOR => PDO: CURSOR_FWDONLY )); $ execRet = $ pdoStatement-> execute ($ mapData); return $ execRet;} // The Field Association array processes public function FDFields ($ data, $ link = ',', $ judge = array (), $ aliasTable = '') {$ SQL =''; $ mapData = array (); foreach ($ data as $ key => $ value) {$ mapIndex = ':'. ($ link! = ','? 'C': ''). $ aliasTable. $ key; $ SQL. =''. ($ aliasTable? $ AliasTable. '.': ''). '''. $ key. '''. ($ judge [$ key]? $ Judge [$ key]: '= '). ''. $ mapIndex. ''. $ link; $ mapData [$ mapIndex] = $ value;} $ SQL = trim ($ SQL, $ link); return array ($ SQL, $ mapData );} public function FDField ($ field, $ value, $ judge = ', $ preMap = 'cn', $ aliasTable = '') {$ mapIndex = ':'. $ preMap. $ aliasTable. $ field; $ SQL = ''. ($ aliasTable? $ AliasTable. '. ':''). '''. $ field. '''. $ judge. $ mapIndex; $ mapData [$ mapIndex] = $ value; return array ($ SQL, $ mapData);} public function FDCondition ($ condition, $ mapData) {if (is_string ($ condition) {$ where = $ condition;} else if (is_array ($ condition) {if ($ condition ['str']) {if (is_string ($ condition ['str']) {$ where = $ condition ['str'];} else {return false ;}} if (is_array ($ condition ['data']) {$ Link = $ condition ['link']? $ Condition ['link']: 'and'; list ($ conSql, $ mapConData) = $ this-> FDFields ($ condition ['data'], $ link, $ condition ['Judge ']); if ($ conSql) {$ where. = ($ where? ''. $ Link :''). $ conSql; $ mapData = array_merge ($ mapData, $ mapConData) ;}} return array ($ where, $ mapData) ;}}?>

7. [File]DPDO. php ~ 1KB

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.