PDOStatement::fetch
PDOStatement::fetch — 从结果集中获取下一行(PHP 5 >= 5.1.0, PECL pdo >= 0.1.0)
说明
语法
mixed PDOStatement::fetch ([ int $fetch_style [, int $cursor_orientation = PDO::FETCH_ORI_NEXT [, int $cursor_offset = 0 ]]] )
从一个 PDOStatement 对象相关的结果集中获取下一行。fetch_style 参数决定 POD 如何返回行。
参数
fetch_style
控制下一行如何返回给调用者。此值必须是 PDO::FETCH_* 系列常量中的一个,缺省为 PDO::ATTR_DEFAULT_FETCH_MODE 的值 (默认为 PDO::FETCH_BOTH )。
cursor_orientation
offset
返回值
此函数(方法)成功时返回的值依赖于提取类型。在所有情况下,失败都返回 FALSE 。
实例
用不同的提取方式获取行
<?php $sth = $dbh->prepare("SELECT name, colour FROM fruit"); $sth->execute(); /* 运用 PDOStatement::fetch 风格 */ print("PDO::FETCH_ASSOC: "); print("Return next row as an array indexed by column name\n"); $result = $sth->fetch(PDO::FETCH_ASSOC); print_r($result); print("\n"); print("PDO::FETCH_BOTH: "); print("Return next row as an array indexed by both column name and number\n"); $result = $sth->fetch(PDO::FETCH_BOTH); print_r($result); print("\n"); print("PDO::FETCH_LAZY: "); print("Return next row as an anonymous object with column names as properties\n"); $result = $sth->fetch(PDO::FETCH_LAZY); print_r($result); print("\n"); print("PDO::FETCH_OBJ: "); print("Return next row as an anonymous object with column names as properties\n"); $result = $sth->fetch(PDO::FETCH_OBJ); print $result->NAME; print("\n"); ?>
以上实例会输出:
PDO::FETCH_ASSOC: Return next row as an array indexed by column name Array ( [NAME] => apple [COLOUR] => red ) PDO::FETCH_BOTH: Return next row as an array indexed by both column name and number Array ( [NAME] => banana [0] => banana [COLOUR] => yellow [1] => yellow ) PDO::FETCH_LAZY: Return next row as an anonymous object with column names as properties PDORow Object ( [NAME] => orange [COLOUR] => orange ) PDO::FETCH_OBJ: Return next row as an anonymous object with column names as properties kiwi
使用一个可滚动游标获取行
<?php function readDataForwards($dbh) { $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY BET'; try { $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); $stmt->execute(); while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT)) { $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n"; print $data; } $stmt = null; } catch (PDOException $e) { print $e->getMessage(); } } function readDataBackwards($dbh) { $sql = 'SELECT hand, won, bet FROM mynumbers ORDER BY bet'; try { $stmt = $dbh->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL)); $stmt->execute(); $row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_LAST); do { $data = $row[0] . "\t" . $row[1] . "\t" . $row[2] . "\n"; print $data; } while ($row = $stmt->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_PRIOR)); $stmt = null; } catch (PDOException $e) { print $e->getMessage(); } } print "Reading forwards:\n"; readDataForwards($conn); print "Reading backwards:\n"; readDataBackwards($conn); ?>
以上实例会输出:
Reading forwards:
21 10 5
16 0 5
19 20 10
Reading backwards:
19 20 10
16 0 5
21 10 5
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对插件窝的支持。如果你想了解更多相关内容请查看下面相关链接