dongyun8075 2013-03-14 05:10 采纳率: 100%
浏览 84
已采纳

PDO类与PDOStatement类之间的关系

I'm a php and mysql beginner, I'm currently self study PDO and confused some concepts:

$dbh = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$sql = "SELECT * FROM users";
$users = $dbh->query($sql);

1.What is the relationship between PDO class and PDOStatement class?

$dbh is the new object of class PDO, but why $users is the PDOStatement object? fetchAll() is the function inside class PDOStatement, but you can use it like this $users->fetchAll(), is $users a PDO or PDOStatement object?

2.Someone said $users is the cursor, once consumed, it won't rewind to the beginning of the resultset.

foreach ($users as $row) {
    print $row["name"] . "<br/>";
}

but why you can use it in a foreach statement? foreach provides a way to iterate over arrays. what is cursor actually? is cursor a pointer?

3.For the pdostatement class, the doc said:

PDOStatement implements Traversable { ... }

why this class implements Traversable interface? is it empty interface?

Thank you for help!

  • 写回答

2条回答 默认 最新

  • dongluanan7163 2013-03-14 05:32
    关注

    According to the documentation, the Traversable interface allows you to use the object into a foreach loop and it's only supposed to be used internally. Think of it as a convenient way of using the PDOStatement.

    Basically, with PDO there is two ways to execute a query, one by using PDO::prepare() & PDOStatement::execute() and the other one by using PDO::query(). The later does prepare/execute in one call.

    PDO::query() and PDO::execute() will not return the results on the other hand the PDOStatement object will allow you to specify the data you want to return. PDOStatement::fetchAll() will allow to define how you want to have your data organized.

    It seems more complicated on first sight but it provides more flexibility.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 写uniapp时遇到的问题
  • ¥15 matlab有限元法求解梁带有若干弹簧质量系统的固有频率
  • ¥15 找一个网络防御专家,外包的
  • ¥100 能不能让两张不同的图片md5值一样,(有尝)
  • ¥15 informer代码训练自己的数据集,改参数怎么改
  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流