zoukankan      html  css  js  c++  java
  • PHP PDO mysql抽象层

    使用PDO构造函数连接数据库及DSN详解

    <?php
    
    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbName=$dbname";
    try{
        $pdo = new PDO($dsn,$user,$pwd);
        echo 'pdo连接数据库成功';
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    页面输出的结果如下图:

    pdo连接数据库成功

    由于数据库服务器只是特定的端口上监听连接请求。每种数据库服务器具有一个默认的端口号(MySQL 是3306),但是数据库管理员可以对端口号进行修改,因此有可能 PHP找不到数据库的端口号,此时就可以在 DSN中包含端口号。比如:

    $dsn="mysql:host=127.0.0.1;port=3306;dbname=admin";

    PDO中获取结果集之fetch()方法详解

    首先创建一个php文件,通过 PDO连接MySQL数据库,然后定义 SELECT查询语句,应用prepare()和execute()方法执行查询操作,接着,通过fetch()方法返回结果集中下一行数据没同事设置结果集以关联数组形式返回,最后通过 while语句完成数据的循环输出,具体代码如下:

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "SELECT * FROM user";
        $res = $pdo->prepare($query);
        $res->execute();
        while($result = $res->fetch(PDO::FETCH_ASSOC)){
            echo $result['username'].' '.$result['password'].' '.$result['email'].'<br>';
        }
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    PDO中获取结果集之fetchAll()方法详解

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "SELECT * FROM user";
        $res = $pdo->prepare($query);
        $res->execute();
        $result = $res->fetchAll(PDO::FETCH_ASSOC);
        for($i=0;$i<count($result);$i++){
            echo $result[$i]['username'].' '.$result[$i]['password'].' '.$result[$i]['email'].'<br>';
        }        
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    PDO中获取结果集之fetchColumn()方法详解

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "select * from user";
        $res = $pdo->prepare($query);
        $res->execute();
        echo $res->fetchColumn(0).'<br>';//返回id
        echo $res->fetchColumn(0).'<br>';
        echo $res->fetchColumn(0).'<br>';
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    PDO中执行SQL语句的三种方法

    第一种方法:exec()方法

    该方法返回执行SQL 语句时受影响的行数,通常用于 INSERT,DELETE和UPDATE语句中。

    <?php
    
    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "INSERT INTO user(username,password,confirm,email) VALUES('cyy01','123','123','965794175@qq.com')";
        $res = $pdo->exec($query);
        echo '插入成功,受影响的行数为:'.$res;
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    第二种方法:query()方法

    query()方法用于返回执行查询后的结果集

    <?php
    
    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "SELECT * FROM user";
        $res = $pdo->query($query);
        print_r($res);
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    注意:

    1、query和exec都可以执行所有的sql语句,只是返回值不同而已。

    2、query可以实现所有exec的功能。

    3、当把select语句应用到 exec 时,总是返回 0

    4、如果要看查询的具体结果,可以通过foreach语句完成循环输出

    第三种种方法:预处理语句:prepare()语句和execute()语句

    还可以通过bindParam()方法来绑定参数给execute()方法

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "SELECT * FROM user";
        $res = $pdo->prepare($query);
        $res->execute();
        while($result = $res->fetch(PDO::FETCH_ASSOC)){
            echo $result['id']." ".$result['username']." ".$result['password'].'<br>';
        }
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    使用默认模式-PDO::ERRMODE_SILENT(PDO中捕获SQL语句中的错误方法一)

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "insert into `user_12`(username,password) VALUES ('cyy02','123')";
        $res = $pdo->prepare($query);
        $res->execute();
        $code = $res->errorCode();
        if(empty($code)){
            echo '插入成功';
        }else{
            var_dump($res->errorInfo());
        }
    }catch(Exception $e){
        echo $e->getMessage().'<br>';
    }

    注意:

    在上面的代码中,在定义 INSERT 添加语句的时候,故意使用了错误的数据表名字user_12(正确的数据表名称是:user),这里是为了测试写的!

    导致错误输出结果如下:

    使用警告模式-PDO::ERRMODE_WARNING(PDO中捕获SQL语句中的错误方法二)

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        //设置为警告模式
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING);
        $query = "select * from user_12";
        $res = $pdo->prepare($query);
        $res->execute();
        while($result = $res->fetch(PDO::FETCH_ASSOC)){
            echo $result['username'];
        }
      echo '程序能够继续执行哦~'; }
    catch(Exception $e){ echo $e->getMessage().'<br>'; }

    注意:

    在上面的代码中,在定义 SELECT 查询语句的时候,我们故意使用了错误的数据表名字user_12(正确的数据表名称是:user),这里是为了测试写的!

    在设置为警告模式以后,如果SQL 语句出现错误将会给出一个提示信息,但是程序仍然能继续执行下去,上面实例得到的结果如下图:

    使用异常模式-PDO::ERRMODE_EXCEPTION(PDO中捕获SQL语句中的错误方法三)

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        //设置为异常模式
        $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
        $query = "delete * from user_12 where id = :id";
        $res = $pdo->prepare($query);
        $id = 5;
        $res->bindParam(':id',$id);
        $res->execute();
    }catch(PDOException $e){
        echo 'error:'.$e->getMessage().'<br>';
        echo 'code:'.$e->getCode().'<br>';
        echo 'file:'.$e->getFile().'<br>';
        echo 'line:'.$e->getLine().'<br>';
        echo 'trace:'.$e->getTraceAsString().'<br>';
    }

    注意:

    在上面的代码中,在定义 DELETE 删除语句的时候,我们故意使用了错误的数据表名字user_12(正确的数据表名称是:user),这里是为了测试写的!

    在设置为异常模式后,执行错误的SQL语句,输出结果如下:

    PDO中错误处理的方法一-errorCode()方法

    在PDO中有两个获取程序中错误信息的方法:errorCode()方法和errorInfo()方法!

    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "DELETE FROM user_12";
        $res = $pdo->query($query);
        echo $pdo->errorCode().'<br>';
    }catch(PDOException $e){
        echo $pdo->errorCode().'<br>';
        echo $e->getMessage().'<br>';
    }

    运行结果如下:

    PDO中错误处理的方法二-errorInfo()方法

    <?php
    
    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        $query = "DELETE FROM user_12";
        $res = $pdo->query($query);
        print_r($pdo->errorInfo());
    }catch(PDOException $e){
        echo $pdo->errorCode().'<br>';
        echo $e->getMessage().'<br>';
    }

    输出的结果如下图所示:

    PDO中的事务处理

    (1) 开启事务——beginTransaction()方法。

    beginTransaction()方法将关闭自动提交(autocommit)模式,直到事务提交或者回滚以后才恢复。

    (2)提交事务——commit()方法

    commit()方法完成事务的提交操作,成功返回true,否则返回false。

    (3)事务回滚——rollBack()方法

    rollBack()方法执行事务的回滚操作。

    <?php
    
    $dbms = 'mysql';
    $dbname = 'test';
    $user = 'root';
    $pwd = '123456';
    $host = 'localhost';
    $dsn = "$dbms:host=$host;dbname=$dbname";
    try{    
        $pdo = new PDO($dsn,$user,$pwd);
        // 开启事务
        $pdo->beginTransaction();
        $query = "insert into user(username,password,confirm,email) VALUES ('cyy03','333','333','965794175@qq.com')";
        $res = $pdo->prepare($query);
        $res->execute();
        if($res->errorCode()){
            echo '数据添加成功';
        }else{
            echo '数据添加失败';
        }
        //事务提交
        $pdo->commit();
    }catch(PDOException $e){
        die($e->getMessage().'<br>');
        //事务回滚
        $pdo->rollBack();
    }

    最后输出的结果如下:数据添加成功

  • 相关阅读:
    JS写游戏
    为运算表达式设计优先级
    原子的数量
    二叉搜索树的范围和
    所有可能的满二叉树
    有效的井字游戏
    站在对象模型的尖端
    执行期语意学
    构造、析构、拷贝语意学
    [CSP-S模拟测试]:序列(二分答案+树状数组)
  • 原文地址:https://www.cnblogs.com/chenyingying0/p/12956722.html
Copyright © 2011-2022 走看看