Home php教程 PHP开发 Summary of PHP data object PDO operation skills

Summary of PHP data object PDO operation skills

Dec 28, 2016 pm 05:09 PM
php pdo

The examples in this article describe the PHP data object PDO operation skills. Share it with everyone for your reference, the details are as follows:

PHP Data Object (PDO) extension defines a lightweight consistent interface for PHP to access the database.

<?php
 try {
  $dsn = "mysql:host=localhost; port=3306; dbname=wsq_hotel; charset=utf-8";
  $user = &#39;root&#39;;
  $psw =&#39;root&#39;;
  $pdo = new PDO($dsn,$user,$psw);
  $sql = &#39;select goods_prices from wsq_goods_info where goods_id=2&#39;;
  // $sql = "show database";
  $res = $pdo->query($sql) or var_dump($pdo->errorInfo());
  // var_dump($res);
  $mon = $res->fetch(PDO::FETCH_ASSOC);
  echo $mon[&#39;goods_price&#39;];
 } catch (PDOException $e) {
  echo $e->getMessage();
 }
?>
Copy after login

PDO operation transaction

//开启事务
beginTransacition()
//回滚
rollback()
//提交
commit()
//判断是否处于事务之中
inTransaction()
Copy after login

Return the ID of the last inserted row

PDO::lastInsertID()
Copy after login

exec() execution

Compared with query(), exec() Returns the number of affected rows

$sql = "insert into table values(&#39;$val&#39;)";
if(false===$pdo->exec($sql)){
 echo &#39;执行失败&#39;;
}
Copy after login

PDO implements pre-compilation

Refers to a syntax for executing sql that pre-compiles the sql structure

If multiple structures are executed For the same SQL, the intermediate result (syntax tree) of compilation should also be consistent, so the same structure can be compiled uniformly and executed with different data each time.

Compile unified structure

$pdoStatement = $pdo->prepare(sql结构)
Copy after login

Bind data to intermediate compilation results

$pdoStatement ->bindValue()
Copy after login

Execution

$pdoStatement ->execute()
//$sql = "insert into table values(null,?)";
$sql = "insert into table values(null,:name)";
$stmt = $pdo->prepare($sql);
//多组数据也是一编译一执行
//$stmt->bindValue(1,&#39;bee&#39;);
$stmt->bindValue(&#39;:name&#39;,&#39;bee&#39;);
$res = $stmt->execute();
var_dump($res);
Copy after login

Pre-compilation can better prevent sql injection, yes Because the user's data is not required to participate in pre-compilation, the structure is fixed during compilation, so the data does not affect the SQL structure.

$pdo->query() and $pdo->execute() If you need to prevent sql injection, you can use $pdo->quote() (its function is to escape first and then add quotes)

Commonly used methods of PDOstatement:

errorInfo()
errorCode()
fetchColumn()
fetch()
fetchAll()
rowCount()
closeCursor()

pdo application

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);
 class PDODB{
  static private $_init;
  private $_host;
  private $_port;
  private $_dbname;
  private $_username;
  private $_password;
  private $_charset;
  private $_dns;
  private $_pdo;
  private function __construct($config){
   $this->_initParamas($config);
   $this->_initDNS();
   $this->_initDriverOptions();
   $this->_initPDO();
  }
  private function __clone(){}
  static public function getInstance($config){
   if(!static::$_init instanceof static){
    static::$_init = new static($config);
   }
   return static::$_init;
  }
  private function _initParamas($config){
   $this->_host = isset($config[&#39;host&#39;])?$config[&#39;host&#39;]:&#39;localhost&#39;;
   $this->_port = isset($config[&#39;port&#39;])?$config[&#39;port&#39;]:&#39;3306&#39;;
   $this->_dbname = isset($config[&#39;dbname&#39;])?$config[&#39;dbname&#39;]:&#39;&#39;;
   $this->_username = isset($config[&#39;username&#39;])?$config[&#39;username&#39;]:&#39;root&#39;;
   $this->_passward = isset($config[&#39;passward&#39;])?$config[&#39;passward&#39;]:&#39;&#39;;
   $this->_charset = isset($config[&#39;charset&#39;])?$config[&#39;charset&#39;]:&#39;utf8&#39;;
  }
  private function _initDNS(){
   $this->_dns = "mysql:host=$this->_host;port=$this->_port;dbname=$this->_dbname";
  }
  private function _initDriverOptions(){
   $this->_driverOptions = array(
    PDO::MYSQL_ATTR_INIT_COMMAND => "set names $this->_charset"
   );
  }
  private function _initPDO(){
   $this->_pdo = new PDO($this->_dns,$this->_username,$this->_passward,$this->_driverOptions) or die("fail");
  }
  public function query($sql){
   if(!$result = $this->_pdo->query($sql)){
    $erro = $this->_pdo->errorInfo();
    echo &#39;失败的语句&#39;.$sql.&#39;<br>&#39;;
    echo &#39;错误代码&#39;.$erro[1].&#39;<br>&#39;;
    echo &#39;错误信息&#39;.$erro[2].&#39;<br>&#39;;
    die;
   }
   return $result;
  }
  public function fetchAll($sql){
   $res = $this->query($sql);
   $list = $res->fetchAll(PDO::FETCH_ASSOC);
   $res->closeCursor();
   return $list;
  }
  public function fetchRow($sql){
   $res = $this->query($sql);
   $row = $res->fetch(PDO::FETCH_ASSOC);
   $res->closeCursor();
   return $row;
  }
  public function fetchOne($sql){
   $res = $this->query($sql);
   $one = $res->fetchColumn();
   $res->closeCursor();
   return $one;
  }
  public function escape_string($data){
   return $this->_pdo->quote($data);
  }
 }
 $config = array(
  "host"=>"localhost",
  "username"=>"root",
  "passward"=>"root",
  "dbname"=>"students"
 );
 $pdo = PDODB::getInstance($config);
 $sql = "select sdept from student where sage=21";
 var_dump($pdo->fetchRow($sql));
?>
Copy after login

The running effect diagram is as follows:

Summary of PHP data object PDO operation skills

I hope this article will be useful to everyone in PHP programming. helped.

For more articles related to summary of PHP data object PDO operation skills, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1672
14
PHP Tutorial
1277
29
C# Tutorial
1257
24