[Instance] in php, the PDO method is used to add, delete, modify, and query databases.

Source: Internet
Author: User
Tags php example

[Instance] in php, the PDO method is used to add, delete, modify, and query databases.
You can easily organize and understand the PDO operation instances. Note that you need to enable the pdo support for php. php5.1 and later versions support database connection Singleton, there are three elements: 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 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 (). '<br/> ');}}}


It is used to process field ing. Using pdo field ing can effectively avoid SQL injection.
// Field associated array processing, mainly used for writing and updating data, the same and or query conditions, arrays that generate 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 (). '<br/>') ;}}$ 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 '). '<br/>'; // update $ 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. '<br/>'; // 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 '). '<br/>'; // 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

Related Article

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.