• PDO 数据访问抽象层


    //PDO
    //数据访问抽象层
    <?php
    
    //1.操作其它数据库
    //2.事务功能
    //3.防止SQL注入攻击
    
    //造PDO对象
    //$dsn = "mysql:dbname=mydb;host=localhost"; //数据源
    //$pdo = new PDO($dsn,"root","123");
    
    //写SQL语句
    //$sql = "select * from nation";
    //$sql = "insert into nation values('n077','数据')";
    
    //执行,返回的是PDOStatement对象
    //$a = $pdo->query($sql); //执行查询
    //$a = $pdo->exec($sql); //执行其他语句
    
    //var_dump($a);
    
    //$arr = $attr->fetchAll(PDO::FETCH_BOTH);
    //var_dump($arr);
    
    
    //事务功能
    //事务:能够控制语句同时成功同时失败,失败时可以回滚
    
    $dsn = "mysql:dbname=mydb;host=localhost";        //数据库名称,服务器
    $pdo = new PDO($dsn,"root","123");
    
    //设置异常模式
    $pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION); 
    
    try
    {
        //开启事务
        $pdo ->beginTransaction(); 
        
        $sql1 = "insert into nation values('n080','是删')";
        $sql2 = "insert into nation values('n070','好几款')";
        $sql3 = "insert into nation values('n075','好几款')";
        
        $pdo->exec($sql1);
        $pdo->exec($sql2);
        $pdo->exec($sql3);               // 三个的执行成功是并的关系,否则出错。
       
        //提交
        $pdo->commit();
    }
    catch(Exception $e)
    {
        //抓住try里面出现的错误,并且处理zv
        //echo $e->getMessage(); //获取异常信息
        
        //回滚
        $pdo->rollBack();
    }
    //final()
    //{
        //最终执行,无论以上try代码有没有出错,都会执行
    //}
    
    
    
    ?>
    
    </body>
    <?php
    
    //预处理语句防止SQL注入
    $dsn = "mysql:dbname=mydb;host=localhost";
    $pdo = new PDO($dsn,"root","123");
    
    //$code = "n005";
    
    //SQL语句里面需要加占位符 ?
    //$sql = "select * from nation where code=?";
    $sql = "insert into nation values(?,?)";
    
    //准备执行,返回PDOStatement对象
    $st = $pdo->prepare($sql);
    
    //调用绑定参数的方法来绑定参数
    //$st->bindParam(1,$code);
    //$st->bindParam(2,$name);
    //$name = "测试1";
    
    //索引数组                      //注意区别
    $attr = array("n006","测试2");
    
    //执行方法
    $st->execute($attr);
    
    //$attr = $st->fetchAll();
    
    //var_dump($attr);
    
    
    
    
    ?>
    <?php
    
    $dsn = "mysql:dbname=mydb;host=localhost";
    $pdo = new PDO($dsn,"root","123");
    
    //占位符是字符串
    $sql = "insert into nation values(:code,:name)";
    
    $st = $pdo->prepare($sql);      //等待执行。prepare准备
    //$st->bindParam(":code",$code,PDO::PARAM_STR);
    //$st->bindParam(":name",$name,PDO::PARAM_STR);
    //$code = "n007";
    //$name = "测试3";
    
    //关联数组                               //与?占位符的区别
    $attr = array("code"=>"n008","name"=>"测试4");
    
    $st->execute($attr);
    
    
    ?>
  • 相关阅读:
    网络编程
    GUI编程
    Java数组
    Day24
    Day23
    Day22
    Day21
    Day20
    Day19
    Day18
  • 原文地址:https://www.cnblogs.com/1358-com/p/6246974.html
Copyright © 2020-2023  润新知