0xx_PDO

Today 1.1 goals

  1. PDO understand the value generated;
  2. PDO understand the three main functions of each class;
  3. PDO master class of the object instance;
  4. Learn to set properties of the PDO principle;
  5. Understand the principles PDOStatement class objects produced;
  6. Master the application fetch data acquisition;
  7. Application of the pretreatment control PDO;
  8. PDO understand the application in the transaction;
  9. Learn three errors in the processing mode PDO;
  10. PDO mastered the use of exceptions;
  11. Understand the meaning of the second package of PDO;
  12. PDO grasp the second package;

1.2 PDO Introduction

1.2.1 connecting to the database way

Method One: mysql extension [this way] has been eliminated php7
Method Two: mysqli extension
Method three: PDO extension

1.2.2 PDO Introduction

PDO (PHP Data Object) extension provides a lightweight PHP access to various databases, the consistency of the interface. No matter what database access, you can go through the operation of the interface consistency.

1.2.3 open PDO extension

Open PDO connection MySQL extension

extension=php_pdo_mysql.dll

1.3 PDO core classes

1, PDO Class: represents a connection between the database and the PHP
2, PDOStatement class
first: a rear query execution data (select, show) for the result set
of the second: pretreatment objects
3, PDOException categories: represents PDO exceptions

1.4 PDO object instantiated

grammar

__construct($dsn,用户名,密码)

1.4.1 DSN

DSN: data source name, a data source name, connection database contains information in the following format:

$dsn=数据库类型:host=主机地址;port=端口号;dbname=数据库名称;charset=字符集

Database type:

MySQL数据库	=>	mysql:
oracle数据库	=>	oci:
SQL Server 		=>sqlsrv:
具体驱动类型参见手册“PDO驱动”

1.4.2 Examples of PDO

Examples of the PDO process is to link the database

<?php
$dsn='mysql:host=localhost;port=3306;dbname=data;charset=utf8';
$pdo=new PDO($dsn,'root','root');
var_dump($pdo); //object(PDO)#1 (0) { } 

1.4.3 Notes

1, if the connection is a local database, host may be omitted

<?php
$dsn='mysql:port=3306;dbname=data;charset=utf8';
$pdo=new PDO($dsn,'root','root');
var_dump($pdo); //object(PDO)#1 (0) { } 

2, if the 3306 port, port may be omitted

<?php
$dsn='mysql:dbname=data;charset=utf8';
$pdo=new PDO($dsn,'root','root');
var_dump($pdo); //object(PDO)#1 (0) { } 

3, charset be omitted, if omitted, the default character encoding used

<?php
$dsn='mysql:dbname=data';
$pdo=new PDO($dsn,'root','root');
var_dump($pdo); 

4, dbname may be omitted, if it is not selected is omitted Database

<?php
$dsn='mysql:';
$pdo=new PDO($dsn,'root','root');
var_dump($pdo); 

5, host, port, dbname, charset case insensitive, there is no order

6, driver name can not be omitted, the colon can not be omitted (as part of the colon is the name of the drive), database-driven only lowercase

1.5 Use PDO

1.5.1 perform data manipulation statements

Methods: $ pdo-> exec ($ sql), perform data add, delete, change the statement executed successfully returns the number of records affected, if the SQL statement error returns false.

<?php
//1、实例化PDO
$dsn='mysql:host=localhost;port=3306;dbname=data;charset=utf8';
$pdo=new PDO($dsn,'root','root');
//2执行数据操作语句
//2.1 执行增加
/*
if($pdo->exec("insert into news values (null,'bb','bbbbbb',unix_timestamp())"))
    echo '自动增长的编号是:'.$pdo->lastInsertId (),'<br>';
*/
//2.2 执行修改
//echo $pdo->exec("update news set title='静夜思' where id in (3,4)");
//2.3 执行删除
//echo $pdo->exec('delete from news where id=5');\
//2.4 完善
$sql="update news set title='静夜思1' where ids in (3,4)";
$rs=$pdo->exec($sql);
if($rs){
    echo 'SQL语句执行成功<br>';
    if(substr($sql, 0,6)=='insert')
        echo '自动增长的编号是:'.$pdo->lastInsertId (),'<br>';
    else
        echo '受到影响的记录数是:'.$rs,'<br>';
}elseif($rs===0){
    echo '数据没有变化<br>';
}elseif($rs===false){
    echo 'SQL语句执行失败<br>';
    echo '错误编号:'.$pdo->errorCode(),'<br>';
    //var_dump($pdo->errorInfo());
    echo '错误信息:'.$pdo->errorInfo()[2];
}

1.5.2 perform data query

Methods: $ pdo-> query ($ sql), returns a PDOStatement objects

<?php
$dsn='mysql:dbname=data;charset=utf8';
$pdo=new PDO($dsn,'root','root');
//1、执行数据查询语句
$stmt=$pdo->query('select * from products');
//var_dump($stmt);        //object(PDOStatement)
//2、获取数据
//2.1  获取二维数组
//$rs=$stmt->fetchAll();  //默认返回关联和索引数组
//$rs=$stmt->fetchAll(PDO::FETCH_BOTH);     //返回关联和索引数组
//$rs=$stmt->fetchAll(PDO::FETCH_NUM);      //返回索引数组
//$rs=$stmt->fetchAll(PDO::FETCH_ASSOC);    //返回关联数组
//$rs=$stmt->fetchAll(PDO::FETCH_OBJ);        //返回对象数组

//2.2  获取一维数组,匹配完成后指针下移一条
//$rs=$stmt->fetch();     //关联和索引数组
//$rs=$stmt->fetch(PDO::FETCH_NUM);   //索引数组
//例题:通过while循环获取所有数据
/*
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
    $rs[]=$row;
}
echo '<pre>';
var_dump($rs);
 */

//3.3  匹配列:匹配当前行的第n列,列的编号从0开始,匹配完毕后指针下移一条
//echo $stmt->fetchColumn();  //获取当前行的第0列
//echo $stmt->fetchColumn(1);  //获取当前行的第1列

//3.4  总行数,总列数
/*
echo '总行数:'.$stmt->rowCount(),'<br>';
echo '总列数:'.$stmt->columnCount();
*/

//3.5 遍历PDOStatement对象(PDOStatement对象是有迭代器的)
foreach($stmt as $row){
    echo $row['proname'],'-',$row['proprice'],'<br>';
}
stdClass类是所有PHP类的父类

1.5.3 PDO operations Affairs

Services: it is a whole or performed together, or rolled back together

Characteristics of the transaction: atomicity, consistency, isolation, permanent

Multiple SQL statements need to be executed as a whole, we need to use the transaction

grammar

start transaction 或 begin		开启事务
commit	提交事务
rollback	回滚事务

example

Create test data

create table bank(
       cardid char(4) primary key comment '卡号',
       balance decimal(10,2) not null comment '余额'
)engine=innodb charset=utf8 comment '银行卡号表'

insert into bank values ('1001',1000),('1002',1)

PDO operations Affairs

<body>
<?php
if(!empty($_POST)){
    $dsn='mysql:dbname=data;charset=utf8';
    $pdo=new PDO($dsn,'root','root');
    $out=$_POST['card_out'];    //转出卡号
    $in=$_POST['card_in'];      //注入卡号
    $money=$_POST['money'];     //金额
    $pdo->beginTransaction();   //开启事务
    //转账
    $flag1=$pdo->exec("update bank set balance=balance-$money where cardid='$out'");
    $flag2=$pdo->exec("update bank set balance=balance+$money where cardid='$in'");
    //查看转出的账号是否大于0,大于0返回true,否则返回false
    $stmt=$pdo->query("select balance from bank where cardid='$out'"); 
    $flag3=$stmt->fetchColumn()>=0?1:0;
    
    if($flag1 && $flag2 && $flag3){
        $pdo->commit ();    //提交事务
        echo '转账成功';
    }
    else{
        $pdo->rollBack ();  //回滚事务
        echo '转账失败';
    }
}
?>
<form action="" method="post">
    转出卡号: <input type="text" name="card_out" id=""> <br>
    转入卡号: <input type="text" name="card_in" id=""> <br>
    金额:<input type="text" name="money" id=""> <br>
    <input type="submit" value="提交">
</form>
</body>

operation result

summary:

 $pdo->beginTransaction()	开启事务
 $pdo->commit ()			提交事务
 $pdo->rollBack()			回滚事务

1.5.4 PDO preprocessing operation

MySQL pretreatment review

Pretreatment benefits: compiled once executed multiple times, to solve the problem of a SQL statement executed multiple times, and improve the efficiency.

Prepared Statements:

prepare 预处理名字 from 'sql语句'

Preprocessing is performed

execute 预处理名字 [using 变量]

Pretreatment of PDO - a placeholder

<?php
    $dsn='mysql:dbname=data;charset=utf8';
    $pdo=new PDO($dsn,'root','root');
    //创建预处理对象
    $stmt=$pdo->prepare("insert into bank values (?,?)");   //?是占位符
    //执行预处理
    $cards=[
        ['1003',500],
        ['1004',100]
    ];
    foreach($cards as $card){
        //绑定参数,并执行预处理,
        //方法一:
        /*
        $stmt->bindParam(1, $card[0]);  //占位符的位置从1开始
        $stmt->bindParam(2, $card[1]);
        $stmt->execute();               //执行预处理
         */
        //方法二:
        /*
        $stmt->bindValue(1, $card[0]);
        $stmt->bindValue(2, $card[1]);
        $stmt->execute();
         */
        //方法三:如果占位符的顺序和数组的顺序一致,可以直接传递数组
        $stmt->execute($card);  
    }

Pretreatment of PDO - parameter placeholder

<?php
$dsn='mysql:dbname=data;charset=utf8';
$pdo=new PDO($dsn,'root','root');
//创建预处理对象
$stmt=$pdo->prepare("insert into bank values (:p1,:p2)");   //:p1,:p2是参数占位符
//执行预处理
$cards=[
    ['p1'=>'1003','p2'=>500],
    ['p1'=>'1004','p2'=>1000]
];
foreach($cards as $card){
    //方法一:
    /*
    $stmt->bindParam(':p1', $card['p1']);
    $stmt->bindParam(':p2', $card['p2']);
    $stmt->execute();
     */
    //方法二:但数组的下标和参数名一致的时候就可以直接传递关联数组
    $stmt->execute($card);
}

summary:

1 is a placeholder ,?

2, the beginning of the colon parameter placeholders

3, $ stmt-> bindParam () and $ stmt-> bindValue () difference

4, pretreatment of benefits

a)提高执行效率
b)提高安全性

1.6 PDO Exception Handling

<?php
try{
    $dsn='mysql:dbname=data;charset=utf8';
    $pdo=new PDO($dsn,'root','root');
    //这是PDO错误模式属性,PDO自动抛出异常
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->query('select * from newsssssss');  //自动抛出异常
} catch (PDOException $ex) {
    echo '错误信息:'.$ex->getMessage(),'<br>';
    echo '错误文件:'.$ex->getFile(),'<br>';
    echo '错误行号:'.$ex->getLine();
}

summary:

1, PDOException PDO exception class is

2, instantiating PDO will automatically throw an exception

3, other operations will not throw an exception, you need to set the abnormal pattern PDO

4, PDO abnormal pattern

PDO::ERRMODE_EXCEPTION	抛出异常
PDO::ERRMODE_SILENT		中断
PDO::ERRMODE_WARNING	警告

1.7 singleton class package MyPDO

1.7.1 Step

1, singleton

2, initialization parameters

3, the database connection

4, executed CRUD

5, the query is executed

a) returns a two-dimensional array

b) Returns the one-dimensional array

c) a return line

1.7.2 code implementation

Part I: single embodiment, initialization parameters, instances of PDO

<?php
class MyPDO{
    private $type;      //数据库类别
    private $host;      //主机地址
    private $port;      //端口号
    private $dbname;    //数据库名
    private $charset;   //字符集
    private $user;      //用户名
    private $pwd;       //密码
    private $pdo;       //保存PDO对象
    private static $instance;
    private function __construct($param) {
        $this->initParam($param);
        $this->initPDO();
    }
    private function __clone() {
    }
    public static function getInstance($param=array()){
        if(!self::$instance instanceof self)
            self::$instance=new self($param);
        return self::$instance;
    }
    //初始化参数
    private function initParam($param){
        $this->type=$param['type']??'mysql';
        $this->host=$param['host']??'127.0.0.1';
        $this->port=$param['port']??'3306';
        $this->dbname=$param['dbname']??'data';
        $this->charset=$param['charset']??'utf8';
        $this->user=$param['user']??'root';
        $this->pwd=$param['pwd']??'root';
    }
    //初始化PDO
    private function initPDO(){
        try{
            $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";
            $this->pdo=new PDO($dsn, $this->user, $this->pwd);
        } catch (PDOException $ex) {
            echo '错误编号:'.$ex->getCode(),'<br>';
            echo '错误行号:'.$ex->getLine(),'<br>';
            echo '错误文件:'.$ex->getFile(),'<br>';
            echo '错误信息:'.$ex->getMessage(),'<br>';
            exit;
        }
    }
}
//测试
$param=array(
);
$mypdo= MyPDO::getInstance($param);
var_dump($mypdo);

Part II: data manipulation

<?php
class MyPDO{
    private $type;      //数据库类别
    private $host;      //主机地址
    private $port;      //端口号
    private $dbname;    //数据库名
    private $charset;   //字符集
    private $user;      //用户名
    private $pwd;       //密码
    private $pdo;       //保存PDO对象
    private static $instance;
    private function __construct($param) {
        $this->initParam($param);
        $this->initPDO();
        $this->initException();
    }
    private function __clone() {
    }
    public static function getInstance($param=array()){
        if(!self::$instance instanceof self)
            self::$instance=new self($param);
        return self::$instance;
    }
    //初始化参数
    private function initParam($param){
        $this->type=$param['type']??'mysql';
        $this->host=$param['host']??'127.0.0.1';
        $this->port=$param['port']??'3306';
        $this->dbname=$param['dbname']??'data';
        $this->charset=$param['charset']??'utf8';
        $this->user=$param['user']??'root';
        $this->pwd=$param['pwd']??'root';
    }
    //初始化PDO
    private function initPDO(){
        try{
            $dsn="{$this->type}:host={$this->host};port={$this->port};dbname={$this->dbname};charset={$this->charset}";
            $this->pdo=new PDO($dsn, $this->user, $this->pwd);
        } catch (PDOException $ex) {
            $this->showException($ex);
            exit;
        }
    }
    
    //显示异常
    private function showException($ex,$sql=''){
        if($sql!=''){
            echo 'SQL语句执行失败<br>';
            echo '错误的SQL语句是:'.$sql,'<br>';
        }
        echo '错误编号:'.$ex->getCode(),'<br>';
        echo '错误行号:'.$ex->getLine(),'<br>';
        echo '错误文件:'.$ex->getFile(),'<br>';
        echo '错误信息:'.$ex->getMessage(),'<br>';
    }
    //设置异常模式
    private function initException(){
        $this->pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
    }

    //执行增、删、改操作
    public function exec($sql){
        try{
            return $this->pdo->exec($sql);
        } catch (PDOException $ex) {
            $this->showException($ex, $sql);
            exit;
        }
    }
    //获取自动增长的编号
    public function lastInsertId(){
        return $this->pdo->lastInsertId();
    }
}
//测试
$param=array(
   
);
$mypdo= MyPDO::getInstance($param);
//echo $mypdo->exec('delete from news where id=6');
if($mypdo->exec("insert into news values (null,'11','1111',unix_timestamp())"))
    echo '自动增长的编号是:'.$mypdo->lastInsertId ();

Part III: Data Query section

<?php
class MyPDO{
   ...
    
    //判断匹配的类型
    private function fetchType($type){
        switch ($type){
            case 'num':
                return PDO::FETCH_NUM;
            case 'both':
                return PDO::FETCH_BOTH;
            case 'obj':
                return PDO::FETCH_OBJ;
            default:
                 return PDO::FETCH_ASSOC;
        }
    }
    //获取所有数据 ,返回二维数组
    public function fetchAll($sql,$type='assoc'){
        try{
            $stmt=$this->pdo->query($sql);  //获取PDOStatement对象
            $type= $this->fetchType($type); //获取匹配方法
            return $stmt->fetchAll($type);
        } catch (Exception $ex) {
            $this->showException($ex, $sql);
        }
    }
    //获取一维数组
    public function fetchRow($sql,$type='assoc'){
        try{
            $stmt=$this->pdo->query($sql);  //获取PDOStatement对象
            $type= $this->fetchType($type); //获取匹配方法
            return $stmt->fetch($type);
        } catch (Exception $ex) {
            $this->showException($ex, $sql);
            exit;
        }
    }
    //返回一行一列
    public function fetchColumn($sql){
        try{
             $stmt=$this->pdo->query($sql);
            return $stmt->fetchColumn();
        } catch (Exception $ex) {
            $this->showException($ex, $sql);
            exit;
        }
        
    }
    
}
//测试
$param=array(
   
);
$mypdo= MyPDO::getInstance($param);
//echo $mypdo->exec('delete from news where id=6');
/*
if($mypdo->exec("insert into news values (null,'11','1111',unix_timestamp())"))
    echo '自动增长的编号是:'.$mypdo->lastInsertId ();
 */

//$list=$mypdo->fetchAll('select * from news');
//$list=$mypdo->fetchRow('select * from news where id=1');
$list=$mypdo->fetchColumn('select count(*) from news');
echo '<pre>';
var_dump($list);

Guess you like

Origin www.cnblogs.com/xeclass/p/12657470.html