0

I want to use a associative array (outcome of a PDO query) in a class, so that I can construct a DIV with some database content.
How to get the array inside the Class? In the while loop I want to make an object, in the Class of this object I want to construct the HTML.

while($data = $stmt->fetch( PDO::FETCH_ASSOC )){ 
    $html = new class;
    echo $html;
}

2 Answers 2

1

If you want your while loop to be able to work about like you've written it, you can write the constructor of the class so that it accepts the data as an argument, then implement the div output in the __toString method.

class HtmlDivFormatter {
    private $data;
    public function __construct($data) {
        $this->data = $data;
    }
    public function __toString() {
        return '<div>' . $this->data['column_name'] . '</div>';
        // whatever HTML you have in mind
    }
}

while ($data = $stmt->fetch( PDO::FETCH_ASSOC )) { 
    $html = new HtmlDivFormatter($data);
    echo $html;
}
Sign up to request clarification or add additional context in comments.

Comments

0

see PDO::FETCH_CLASS or PDO::FETCH_INTO more info here http://php.net/manual/en/pdostatement.fetch.php and this PHP PDO fetching into objects

and some example code:

<?php
$sql = 'SELECT firstName, lastName FROM users';

$stmtA = $pdo->query($sql);
$stmtA->setFetchMode(PDO::FETCH_CLASS, 'Person');

$objA = $stmtA->fetch();
var_dump($objA);

//first create the object we will fetch into
$objC = new Person;
$objC->firstName = "firstName";
$objC->lastName = "lastName";

$stmtC = $pdo->query($sql);
$stmtC->setFetchMode(PDO::FETCH_INTO, $objC);

$objC = $stmtC->fetch(); // here objC will be updated
var_dump($objC);


class Person{
    public $firstName;
    public $lastName;
}

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.