[Instance]php the PDO way realizes the database to delete and change to investigate

Source: Internet
Author: User
Tags dsn getmessage php example prepare

Collation of the more easily understood PDO Operation example, note that need to open PHP PDO support, php5.1 above version supports the implementation of database connection Singleton, there are three-factor static variables, static instantiation method, private constructor dpdo.php
PDO Operation class//author Http://www.lai18.comclass dpdo{private $DSN;  Private $DBUser;  Private $DBPWD;  Private $longLink;  Private $pdo;    Private constructors prevent direct instantiation of private function __construct ($DSN, $DBUser, $DBPwd, $longLink = False) {$this->dsn = $DSN;    $this->dbuser = $DBUser;    $this->dbpwd = $DBPWD;    $this->longlink = $longLink;  $this->connect (); }//Private null clone function prevents the clone of private function __clone () {}///Static instantiation function returns a PDO object static public function instance ($DSN, $DBUser, $D Bpwd, $longLink = False) {static $singleton = array ();//static function is used to store the instantiated object $singIndex = MD5 ($dsn. $DBUser, $DBPwd. $l    Onglink);    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/> '); }  }}


For working with field mappings and using PDO's field mappings, you can effectively avoid SQL injection
field associative array processing, primarily used to write and update data, query conditions with and OR or, generate an array of SQL statements and mapped 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); }//For handling a single field handling 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); }//Using the new method can easily generate query conditions and 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); }


The concrete realization db.php of adding and deleting and checking
Traversal of the database//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, ten), $dataMode = Pdo::fetch_assoc, $preTy PE = 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) && $conditi      ON) {$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 file test.php
PDO operation Class-Test PHP example//author http://www.lai18.comheader ("content-type:text/html; Charset=utf-8 ");d efine (' 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, +), $inData [' b '] = rand (1, +), $inData [' c '] = rand (1,200). ‘.‘ . Rand (1,100); $ret = $DB->insert (' A ', $inData); Echo ' Insert '. ($ret? ' Success ': ' Failure '). ' <br/> ';//Update $upcondata[' a '] =: $upConJudge [' a '] = ' < '; $upConData [' b '] = [] $upConJudge [' b '] = ' > '; list ( $UPCONSTR, $mapUpConData) = $DB->fdfield (' B ', $, ' < ', ' GT '); $condition = Array (' str ' = = $upConStr, ' data ' =& Gt $upConData, ' Judge ' + $upConJudge, ' link ' = ' and '), $upData [' a '] = rand (1, ten); $upData[' b '] = 1; $upData [' c '] = 1.00; $changeRows = $DB->update (' A ', $upData, $condition, $mapUpConData); Echo ' update line number: '. (int) $changeRows. ' <br/> ';//delete $delval = rand (1), List ($delCon, $mapDelCon) = $DB->fdfield (' A ', $delVal); $delRet = $DB Delete (' A ', $delCon, $mapDelCon); Echo ' Delete a= '. $delVal. ($delRet? ' Success ': ' Failure '). ' <br/> '; Query $data[' a '] = ' ten '; $judge [' a '] = ' > '; $data [' b '] = ' + '; $judge [' b '] = ' < '; list ($CONSQL, $mapConData) = $DB->f Dfields ($data, ' and ', $judge); $mData = $DB->fetch (' select * from a where '. $conSql. ' ORDER by ' a ' desc ', $mapConData); Var_dump ($mData);


The above mentioned is the whole content of this article, I hope you can like.

Reference Source:
The method of PDO in PHP to realize the deletion and modification of database
Http://www.lai18.com/content/422492.html

[Instance]php the PDO way realizes the database to delete and change to investigate

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.