Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to populate class with constructor using FETCH_INTO of PDO:

class user
{
    private $db;
    private $name;

    function __construct($id)
    {
        $this->db = ...;

        $q = $this->db->prepare("SELECT name FROM users WHERE id = ?");
        $q->setFetchMode(PDO::FETCH_INTO, $this);
        $q->execute(array($id));

        echo $this->name;
    }
}

This does not work. No error, just nothing. Script has no errors, FETCH_ASSOC works fine.

What is wrong with FETCH_INTO?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
300 views
Welcome To Ask or Share your Answers For Others

1 Answer

You have two errors in your code:

1) You forgot $q->fetch()

 ...
 $q->execute(array($id));
 $q->fetch(); // This line is required

2) But even after adding $q->fetch() you'll get this:

Fatal error: Cannot access private property User::$name in ...

So, as you can see, PDO cannot access private members even if it is called inside class method.

Here is my solution:

...
$q->execute(array($id));
$q->setFetchMode(PDO::FETCH_ASSOC);
$data = $q->fetch();
foreach ($data as $propName => $propValue)
{
    // here you can add check if class property exists if you don't want to
    // add another properties with public visibility
    $this->{$propName} = $propValue;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...