【PHP自学笔记】第十四章 PDO数据库抽象层

来源:互联网 发布:华为网络管理平台价格 编辑:程序博客网 时间:2024/06/01 11:44

第14章 PDO数据库抽象层

1.PDO接口对数据库进行操作,简化代码。无需再使用mysq_*函数等。

2.安装方法 PDO在php.ini中进行配置,extension=php_pdo.dll,支持MYSQL数据库则加载extension=php_pdo_mysql.dll(删除注释符 ; )


3.本章代码

<?php

         $dbms='mysql';

         $dbName='db_database';

         $user='root';

         $pwd='111';

         $host='localhost';

         $dsn="$dbms:host=$host;dbname=$dbName";

         $query="select* from tb_user";

                   try{

                            $pdo=newPDO($dsn,$user,$pwd);         //      PDO构造参数链接数据库,为数据库类型:主机名称、数据库名、用户名、密码

                            $result=$pdo->query($query);

                            foreach($resultas $row){

                            ?>

                                     <tr><?phpecho $row['id'];?>;</tr>

                                     <tr><?phpecho $row['username'];?></tr>

                            <?php

                            }

                            $code=$result->errorCode();//默认模式——PRO::ERRMODE_SELIENT,只设置errorCode(),不作其他操作

                           

                   }catch(PDOException$e){//警告模式——PRO::ERRMODE_WARNING,产生一个PHP警告,程序继续按照其方式运行

                            die("Error!:".$e->getMessage()."<br/>");

                   }catch(PDO:ERRMODE_EXCEPTION$e)}{//异常模式——PRO::ERRMODE_EXCEPTION,脚本中断

                            echo"Error:".$e->getMessage()."<br/>";

                   }

                  

        

        

         /*其他常用操作*/

         $query1="select* from tb_user";

         $result=$pdo->prepare($query1);

         $result->execute();

         while($res=$result->fetch(PDO::FETCT_ASSOC)){  //fetch()获取结果集的下一行,循环输出关联数组

                   ?>

                   <tr>

                            <td><?phpecho $res['id'];?></td>

                   </tr>

                   <?php

        

         while($res=$result->fetchAll(PDO::FETCH_ASSOC))       //fetchAll()获取结果集中所有行

         for($i=0;$i<count($res);$i++){

                   ?>

                   <tr>

                            <td><?phpecho $res['id'];?></td>

                   </tr>

                   <?php

         }

        

         }

                  

                   ?>

原创粉丝点击