I noticed PDO::FETCH_INTO
fetch mode doesn't work inside PDOStatement::fetch()
but in the manual it says you can use PDO::FETCH_INTO
with PDOStatement::fetch()
.
I was trying to do: $query->fetch( PDO::FETCH_INTO, $user );
This returns: PDOStatement::fetch() expects parameter 2 to be long, object given
Wouldn't that mean the manual is kind of misleading? And what would be the proper way of using PDO::FETCH_INTO
in this case?
Try this way:
$stmt->setFetchMode(PDO::FETCH_INTO, $user);
$user = $stmt->fetch();
UPDATE:
If you have private/protected properties with public setters (which is recommended) instead of public properties, use FETCH_CLASS instead:
class User {
protected $username;
public setUsername($username) {
$this->username = $username;
}
...
}
...
$stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
$user = $stmt->fetch();
UPDATE 2:
Using PDO::FETCH_CLASS, you don't even need the setter (EDIT: don't need the setter for PDO, which is good for id fields):
class User {
protected $username;
...
}
...
$stmt->setFetchMode(PDO::FETCH_CLASS, 'User');
$user = $stmt->fetch();
UPDATE 3: see full example here: http://pastebin.com/LneAj0xn
Please note that PDOStatement::fetch()'s second argument is cursor_orientation
.
You probably want something like this:
$user = $query->fetch(PDO::FETCH_INTO);