[Instance] using PDO in php to add, delete, modify, and query databases

Source: Internet
Author: User
[Instance] the PDO operation instance in php that is easier to understand for database addition, deletion, modification, and query. Note that you need to enable PDO support for php, php5.1 and later versions support single-instance database connection, including three static variables, static instantiation methods, and private constructor DPDO. php
// PDO operation class // author http://www.lai18.comclass DPDO {private $ DSN; private $ DBUser; private $ DBPwd; private $ longLink; private $ pdo; // private constructor prevents private function _ construct ($ dsn, $ DBUser, $ DBPwd, $ longLink = false) {$ this-> DSN = $ dsn; $ this-> DBUser = $ DBUser; $ this-> DBPwd = $ DBPwd; $ this-> longLink = $ longLink; $ this-> connect () ;}// the private empty clone function prevents the cloned private function _ clone () {} // The static instantiation function returns a pdo object static public function instance ($ dsn, $ DBUser, $ DBPwd, $ longLink = false) {static $ singleton = array (); // the static function is used to store the instantiated object $ 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 of the same and or, and generate an array of SQL statements and ing fields // author http://www.lai18.com 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
// Database traversal // author http://www.lai18.compublic 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
// PDO operation class-test PHP example // author http://www.lai18.comheader ("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.

Reference Source:
Use PDO in php to add, delete, modify, and query databases
Http://www.lai18.com/content/422492.html

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.