_php example of adding and deleting database by PDO method in PHP

Source: Internet
Author: User
Tags dsn
Need to open PHP for PDO support, php5.1 above version support

Implement database connection Singleton, there are three-factor static variable, static instantiation method, private constructor dpdo.php

Class 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 (). '
'); } }}

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 public function Fdfields ($data, $link = ', ', $judge = Array (), $a    liastable = ') {$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)) {$WH ere = $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 specific implementation of adding and removing changes db.php

Public function Fetch ($sql, $searchData = Array (), $dataMode = Pdo::fetch_assoc, $preType = Array (Pdo::attr_cursor-P      Do::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

Header ("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 (). '
'); }} $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 '). '
';//Update $upcondata[' a '] =: $upConJudge [' a '] = ' < '; $upConData [' b '] = +; $upConJudge [' b '] = ' > '; list ($UPCONSTR, $ Mapupcondata) = $DB->fdfield (' B ', $, ' < ', ' GT '); $condition = Array (' str ' = = $upConStr, ' data ' = $upConDa TA, ' judge ' = $upConJudge, ' link ' = ' and '), $upData [' a '] = rand (1, ten); $upData [' b '] = 1; $upData [' c '] = 1.00; $chan Gerows = $DB->update (' A ', $upData, $condition, $mapUpConData); Echo ' update line number: '. (int) $changeRows. '
';//delete $delval = rand (1, ten); list ($delCon, $mapDelCon) = $DB->fdfield (' A ', $delVal); $delRet = $DB->delete (' A ', $ Delcon, $mapDelCon); Echo ' Delete a= '. $delVal. ($delRet? ' Success ': ' Failure '). '
'; 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.

  • 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.