1

I am writing this comment class:

class Comment {

    public $id;
    public $post_id;
    public $name;
    public $email;
    public $website;
    public $body;
    public $date;
    public $ip_address;
    public $status;

    function __construct($id) {

        global $db;

        $resc = $db->query("SELECT * FROM blog_comments WHERE id='$id' LIMIT 1");

        while($row = $db->fetch_assoc($resc)) {
            while ($comment = current($row)) {
                $key = key($row);
                $this->$key = $comment{$key};
                next($row);
            }
        }
    }
}

Here is what the query inside the constructor will return when run in the database:

query results http://17webshop.com/wp-content/uploads/2009/10/Picture-2.png

But when I run it, this is what print_r(new Comment(1)); spits out:

Comment Object
(
    [id] => 1
    [post_id] => 1
    [name] => J
    [email] => j
    [website] => h
    [body] => b
    [date] => 1
    [ip_address] => :
    [status] => 1
)

Any ideas why I'm only getting the first character of each field?

Thanks.

1
  • Were you a Perl programmer, by any chance? Commented Oct 21, 2009 at 21:48

3 Answers 3

6

You want

$comment[$key]

$comment{$key} will give you the nth character of a string. Since $key itself is a string, PHP converts that to an integer 0 and you get the first char.

Sign up to request clarification or add additional context in comments.

1 Comment

The integer value of those keys is 0, which is also the index of the first character of a string.
3

current/next is painful, and I'm not sure what's with the {} dereferencing.

Why not just:

$resc = $db->query("SELECT * FROM blog_comments WHERE id='$id' LIMIT 1");

while($row = $db->fetch_assoc($resc)) {
    foreach($row as $key=>$value){
       $this->$key = $value;
    }
}

3 Comments

you know, i had always wondered what the difference was between [] and {}. Thank you. and yes, this solution is excellent.
See mike B's answer, which is really a more concise answer. I thought that {} would select a single char, but was too lazy to look it up.
Here's the reference: php.net/manual/en/…
2

I think you need to change this line:

$this->$key = $comment{$key};

with:

$this->$key = $comment[$key];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.