Question

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!

Was it helpful?

Solution

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.

OTHER TIPS

All that mess is called "syntax sugar" and intended to sweeten a developer's life, though in real it makes taste too sugary to the point of disgust.

So, there are two kinds of object's characteristics - natural and unnatural ones.
And all your confusion come from the latter.

In your place I'd just forget of them, using objects straight way.

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

That's 2 different classes. They serve different purposes. Like in old mysql you had connection resource and result resource. You have only one connection/PDO instance, but there can be any number actual query results/stmt classes.

but why you can use it in a foreach statement?

That's the very syntax sugar I talked above. They just added such a possibility to the statement object.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top