PDO is a public class for mysql database operations. we can directly use pdo to operate databases without having to customize the class, but in the default php configuration, pdo is not enabled, so we must first in php. enable it in ini. You need to enable pdo support for php and php5.1 and later versions.
Database Connection Singleton is implemented, including three elements: static variables, static instantiation methods, and private constructor DPDO. php.
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 ().'
');}}}
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 );}
Detailed implementation of addition, deletion, modification, and query in DB. php
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; } }
Test. php
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 ').'
'; // Upgrade $ upConData ['A'] = 100; $ upConJudge ['A'] =' <'; $ upConData [' B '] = 30; $ upConJudge ['B'] = '>'; list ($ upConStr, $ mapUpConData) = $ DB-> FDField ('B', 200, '<', 'GT '); $ condition = array ('str' => $ upConStr, 'data' => $ upConData, 'Judge' => $ upConJudge, 'link' => 'and'); $ upData ['A'] = rand (1, 10); $ upData ['B'] = 1; $ upData ['c'] = 1.00; $ changeRows = $ DB-> update ('A', $ upData, $ condition, $ mapUpConData); echo 'number of updated rows :'. (int) $ changeRows.'
'; // Delete $ delVal = rand (1, 10); list ($ delCon, $ mapDelCon) = $ DB-> FDField ('A', $ delVal ); $ delRet = $ DB-> delete ('A', $ delCon, $ mapDelCon); echo 'delete a = '. $ delVal. ($ delRet? 'Success': 'failed ').'
'; // Query $ data ['A'] = '10'; $ judge ['A'] ='> '; $ data ['B'] = '000000'; $ judge ['B'] = '<'; list ($ conSql, $ mapConData) = $ DB-> FDFields ($ data, 'and', $ judge); $ mData = $ DB-> fetch ('select * from a where '. $ conSql. 'order by 'a 'desc', $ mapConData); var_dump ($ mData );
The above is all the content of this article. I hope you will like it.