入门PHP就来我这(高级)18 ~ 获取结果集

有胆量你就来跟着路老师卷起来! -- 纯干货,技术知识分享

路老师给大家分享PHP语言的知识了,旨在想让大家入门PHP,并深入了解PHP语言。 

 


 1 PDO中获取结果集

在PDO中获取结果集常用3中方法:fetch()方法、fetchAll()方法和fetchColumn()方法。

1.1 fetch()方法

fetch()方法可以获取结果集中的下一行记录,其语法格式如下:

mixed PDOStatement::fetch([int $fetch_style [,int $cursor_orientation [,int $cursor_offset]]]);

其中,参数fetch_style是控制结果集的返回方式,其可选方式如下表所示:

其中cursor_orientation是PDOStatement对象的滚动游标,可用于获取指定的一行。

参数cursor_offset:游标的偏移量。 

 案例:使用fetch()方法获取会员列表:

创建数据库表member:

drop table if exists `member`;
create table `member`(
`id` int(8) not null auto_increment,
`nickname` varchar(200) not null,
`email` varchar(200) default null,
`phone` varchar(11) default null,
`level` char(10) default null,
primary key (`id`)
)engine=MyISAM auto_increment=1 default charset=utf8;

insert into `member` values('1','路飞','lufei@163.com','13011111111','A');
insert into `member` values('2','索隆','suolong@163.com','13022222222','B');
insert into `member` values('3','娜美','namei@163.com','13033333333','C');
insert into `member` values('4','山治','shanzhi@163.com','13044444444','D');

创建index.php逻辑层查询数据库数据。


<?php
    require "config.php";

    try{
        //实例化PDO对象,采用new的方式
        $pdo = new PDO(DB_DSN,DB_USER,DB_PWD);
    } catch (PDOException $th) {
        echo $th->getMessahe()."<br>";
    }

    $sql = 'select * from member';

    $result = $pdo->prepare($sql);
    $result->execute();
    include_once('lists.html');
?>

 其中的config.php配置的是数据库的基本信息,内容如下:

<?php
  define('DB_HOST','localhost');
  define('DB_USER','root');
  define('DB_PWD','passwd');
  define('DB_NAME','db_test');
  define('DB_PORT','3306');
  define('DB_TYPE','mysql');
  define('DB_CHARSET','utf8');
  define('DB_DSN',"mysql:host=".DB_HOST.";dbname=".DB_NAME.";charset=".DB_CHARSET);
?>

我们要显示到页面上,创建页面html文件,命名为lists.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>会员列表</title>
  <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">

</head>
<body>
  <div class="container">
    <div class="col-sm-offset-2 col-sm-8">
      <div class="panel panel-default">
        <div class="panel-heading">
          大V的会员列表
        </div>
        <div class="panel-body">
          <table class="table table-striped task-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>昵称</th>
                <th>邮箱</th>
                <th>电话</th>
                <th>等级</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <?php while($row=$result->fetch(PDO::FETCH_ASSOC)) { ?>
              <tr>
                <td class="table-text">
                    <?php echo $row['id'] ?>
                </td>
                <td class="table-text">
                    <?php echo $row['nickname'] ?>
                </td>
                <td class="table-text">
                    <?php echo $row['email'] ?>
                </td>
                <td class="table-text">
                    <?php echo $row['phone'] ?>
                </td>
                <td class="table-text">
                    <?php echo $row['level'] ?>
                </td>
                <td>
                    <button class="btn btn-info edit">编辑</button>
                    <button class="btn btn-danger delete">删除</button>
                </td>
              </tr>
              <?php } ?>
            </tbody>
          </table>
        </div>
      </div>

    </div>
  </div>
  
</body>
</html>

运行http://域名/index.php结果如下:

1.2 fetchAll()方法 

fetchAll()方法可以获取结果集中的所有行。语法格式如下:

array PDOStatement::fetchAll ([int $fetch_style[,int $column_index]]);
//fetch_style 控制结果集中数据的显示方式
//column_index 字段的索引
//返回值是一个包含结果集中所有数据的二维数组。

案例:我们利用fetchAll()获取大V会员的列表:

此时需要改变的地方就是index.php的逻辑和lists.html遍历逻辑。

<?php
    require "config.php";

    try{
        //实例化PDO对象,采用new的方式
        $pdo = new PDO(DB_DSN,DB_USER,DB_PWD);
    } catch (PDOException $th) {
        echo $th->getMessahe()."<br>";
    }

    $sql = 'select * from member';

    $result = $pdo->prepare($sql);
    $result->execute();
    $data = $result->fetchAll(PDO::FETCH_ASSOC);//获取全部数据
    include_once('lists.html');
?>

lists.html里需要改变的唯一地方就是:

 结果不变:

1.3 fetchColumn()方法  

fetchColumn()方法可以获取结果集中下一行指定列的值。语法如下:

string PDOStatement::fetchColumn([int $column_number]);
//column_number是列的索引值,该值从0开始。如果省略该参数则从第一列开始取值。

案例:我们使用该方法获取大V会员列表的会员名。

index.php逻辑改变如下:

<?php
    require "config.php";

    try{
        //实例化PDO对象,采用new的方式
        $pdo = new PDO(DB_DSN,DB_USER,DB_PWD);
    } catch (PDOException $th) {
        echo $th->getMessahe()."<br>";
    }

    $sql = 'select nickname from member';

    $result = $pdo->prepare($sql);
    $result->execute();
    include_once('lists.html');
?>

lists.html里的改变如下:

<tbody>
   <tr>
      <td class="table-text">
          <?php echo $result->fetchColumn() ?>
       </td>
   </tr>
   <tr>
      <td class="table-text">
          <?php echo $result->fetchColumn() ?>
       </td>
   </tr>
   <tr>
      <td class="table-text">
          <?php echo $result->fetchColumn() ?>
       </td>
   </tr>
   <tr>
      <td class="table-text">
          <?php echo $result->fetchColumn() ?>
       </td>
   </tr>
   <tr>
      <td class="table-text">
          <?php echo $result->fetchColumn() ?>
       </td>
   </tr>
   
</tbody>

结果展示如下:

下一篇 PDO捕获sql错误


大家如果喜欢技术,并想有个好的交流平台可以关注我的 我的知乎首页,会不定期分享本人觉得比较好的技术类电子书。
另外,自己创建的一个技术qq群,玩转技术群,该群里功能:分享技能,电子书,源代码,以及兼职项目等交流,欢迎大家加入一起交流。

 

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 01:02:01       67 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 01:02:01       72 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 01:02:01       58 阅读
  4. Python语言-面向对象

    2024-07-10 01:02:01       69 阅读

热门阅读

  1. 反向业务判断逻辑

    2024-07-10 01:02:01       21 阅读
  2. 决策树构建精要:算法步骤与实现细节

    2024-07-10 01:02:01       21 阅读
  3. 我们为什么要学数据库?

    2024-07-10 01:02:01       20 阅读
  4. redis的setnx实现分布式锁

    2024-07-10 01:02:01       30 阅读
  5. Bert 变种, T5模型

    2024-07-10 01:02:01       21 阅读
  6. Docker实战教程(一)

    2024-07-10 01:02:01       24 阅读
  7. Visual Studio编译优化选项

    2024-07-10 01:02:01       19 阅读
  8. Pywinauto:强大的Windows 应用程序测试工具

    2024-07-10 01:02:01       23 阅读